primopydocuments and notebooks
A document is text to read beside the editor: a worksheet, a chapter of notes, a Jupyter notebook, a short course. It opens on a tab of its own, and its code examples run right where they are written, in the same Python as your own code. This page is about reading one, writing one, and getting one out again. The handbook covers the rest of the editor.
This page is a document itself. Open it in the editor and every example on it can be run with Run here, which is the quickest way to see what the sections below describe.
If a teacher sent you a document, section 1 is all you need. If you teach, sections 2 to 4 say how a notebook, a Quarto or R Markdown file, or a Markdown file of your own becomes a document, and how to hand it out.
Contents#
1Reading a document#
How one arrives#
- New. The + at the end of the file tabs opens Add to the project. Pick Document, give it a name such as
notes.md, and tick Fill with example content to start from the example document instead of an empty one. The new document opens in the Document tab, where Edit changes its Markdown. Section 3 says what goes in it. The example document, "A year in numbers", is also on the homepage, and opens from this link: the example document. - A link. A link whose address ends in
#md=…or#mdz=…carries the whole document, pictures and data files included. A link ending in#mdu=/path/notes.mdnames a Markdown file on the primopy site, which the editor fetches; that is how the lessons and this page open. Nothing is uploaded either way: the document is in the link, or on the site. Either opens as a project of its own, and the same link again is that project. - A file. Drag a
.mdfile onto the editor, or pick one with Files from this computer… under the + at the end of the file tabs (or, for a project of its own, From files or a ZIP… in the projects list). A Jupyter notebook (.ipynb), a Quarto file (.qmd) or an R Markdown file (.Rmd) opens the same way; see section 2. The file joins your project's files as a chapter of its document, in its place by the order of the names; your own files stay as they are, and Undo takes the file out again. - A folder. Drag a folder onto the editor. Its files become files of your project, and its Markdown, Quarto, R Markdown and notebook files, at its top and in its folders, are the chapters of the document: the ones at the top first, in the order of their names, with numbers counted as numbers, so
2-loops.mdcomes before10-classes.md, then each folder's (see Chapters in folders). Pictures the Markdown shows come with it, and so does everything else in the folder, such as the program an exercise asks you to write: they are among your files as usual. - A zip. A zip of such a folder opens as the folder would, and so does a repository downloaded from GitHub as a ZIP: dropped on the project button, as a project of its own, or on a project that is still its empty file. On a project with something in it, a zip is unpacked into a folder named after it, and its Markdown files and notebooks are chapters there, in that folder's place among the document's chapters.
The status line under the editor says what was opened. A document is not kept apart from your project: its files are among yours, and everything below about files holds for them.
The document tab#
The document takes the place of the editor, and its tab stands first in the row of file tabs, with the document's title on it: its first # heading; without one, its first heading of any level, or else the file's name. Click a file tab to go to your code, and the document's tab to come back to it. The tab stays for as long as the document is open. The document's files do not appear among your file tabs: they are shown only here. They are listed in the project's tree (the list the project button opens), where you can rename or delete one, and leave it out of the document with its book (open: a chapter; closed: not).
Each # heading starts a chapter, and one chapter is on screen at a time. ☰ at the top left shows or hides the contents: every chapter, and the sections of the one you are reading. Where the chapters are in more than one folder, or a table of contents has parts, the contents are grouped under captions (see Chapters in folders). Under each chapter, two buttons go to the chapter before and the one after, each with its title. On a narrow screen the contents lie over the text and close again once you pick something.
</> on the tab, beside the pencil, takes the code of every cell that runs off the page, its title bar and buttons with it, and puts it back when pressed again: what is left is the text and what the cells printed and drew. Exercises, and code that is only there to be read, stay. A cell that ends in an error is shown again, with its code. The browser remembers your choice for that document. The chevron at the left of a cell's title bar folds just that cell's code under its title bar, which keeps its buttons.
Printing (Ctrl/Cmd+P) prints the document as you see it, every chapter, without the buttons and without the code you have hidden. With a file open in the editor instead, it prints that file, with its lines numbered and coloured as in the editor.
Running the examples#
Every Python example in a document that can run has buttons in its title bar.
- Run here runs the example where it is. What it prints goes to the Output tab under the editor: lines for the console print below what is already there, each line shown after
>>>as at the prompt, while a program clears the tab first, as Run does. A plot goes to Plots, aplotlyfigure too (fromfig.show(), or left as the value of a console line), drawn there as a live chart you can point at and zoom, never under the cell; a drawing goes to Draw. While it runs, the button turns into Stop. - Console, on lines meant for the console, puts them at the console prompt instead, where Enter runs one at a time.
- Open, on a program, opens it in the editor, where you can record it and step through it. One with notes on what to watch is recorded as it opens. Your own program files go away for the moment, while the document stays, and Undo brings them back.
- Watch, on a program with notes on what to watch, records it where it is and plays it back under its code: the line it stands on is lit in the frame, and the tape below walks the run. Drag the tape, use Back and Step, or the arrow keys. The note for that moment is above the tape, and under it are the variables, with the ones the step changed marked, and what the program had printed by then. Open on the player takes the example to the editor at that same step, where the call stack and every variable are. Your own files and tabs stay as they are, as with Run here.
- Copy copies the code.
There are two kinds of example. Lines for the console are the cells of a notebook: they run in the console's names, so what one defines, the next can use, and you can look at all of it at the prompt. Here are two:
prices = [4.50, 2.20, 3.80]total = sum(prices)
print(f"Total: {total:.2f}")Total: 10.50The box under the second, captioned output, is what that cell printed when the document was written. It stays as it is: when you run the cell, its output goes to the Output tab, not under the cell.
A program is a whole program, main.py and any files that come with it. Run here runs it as Run would run your own, among your files, with the example's files laid over them, and leaves your tabs as they are. Afterwards its variables are the console's, as after a Run.
Cells catch up#
Press Run here on the second cell above before running the first, and it still works. A cell first runs every cell above it that has not run yet, in the order they stand, and then itself. In the Output tab a thin line sets off what the cells above printed from what the one you pressed printed; hold the pointer on a line to see which is which.
This goes back to the start of the file the cell is in, to a program example, or to a cell marked fresh by its author, whichever comes first; a program example or a fresh cell there runs too, if it has not run yet. It never goes into another file: each file of a document runs on its own, as each page of a Jupyter Book does, so a chapter file that needs an import or some data sets them up itself. The chapters of one file, its # headings, run as one. A cell that has run wears a small dot beside its buttons; one that ended in an error wears a red one. When a cell above ends in an error, the cells below it do not run, and the status line says which one it was. The dots go when the console's names go: after your own Run, after a program example, or after %reset at the console, every cell counts as not run again.
Changing an example#
Click into an example and you can change its code, there in the document. Ctrl/Cmd+Enter runs it. Enter makes a new line, as in the editor; Shift+Enter runs the line the caret is on: in console lines it then goes on to the next, as Enter at the prompt does, and in a program it runs the line at the console and in your project's folder, where the example's own extra files are not. Escape leaves the code. A changed example is a draft: it says edited, lifts off the page with a shadow, and is kept with your project, so it survives a reload, but it is not in the document's file yet. The tick in its title bar takes the draft into the file, then runs that cell and every cell after it again, in order (cells above that have not run run first), and saves each one's output under it as it is made, so the document never shows an output its code did not make. Discard drops the draft and brings the document's code back; Undo puts it back. A cell that ends in an error stops the run there with the error saved under it; the cells after it show Out of date in place of their old output, with a tick of their own that runs them again. Stop stops the run the same way. A cell further down that holds a draft of its own runs that draft, which is not in the file, so it keeps Out of date until its own tick. A tab that only shows the project cannot change cells. If the cell's place in its file cannot be found again, the tick is off and its title says why.
The document's files#
The document is the Markdown, Quarto, R Markdown and notebook files of your project, .md, .markdown, .qmd, .Rmd and .ipynb, at the top and in folders, unless a table of contents says which they are. Together they are one document, a chapter for each # heading, the files at the top first, in the order of their names (numbers as numbers; an index file first, then a README), then each folder's. A file without a # heading is one chapter, titled from its name. The pictures and data a document carries, the helpers.py a notebook imports and the data/scores.csv its cells read, are files of the project too, in the tabs, in a download, in a link and in a folder like any file. Dropping another Markdown file adds a chapter. A link that carries a document opens it as a project of its own, so its files never meet yours; the same link again is the same project, and Start over puts the document back as the site has it now.
Chapters in folders#
A chapter can be in a folder, at any depth the editor reads a folder to, as a book downloaded as a ZIP keeps its notebooks in a chapters/ folder. A file is no chapter when a part of its path starts with . or _, as _build/ and .ipynb_checkpoints/ do, or when it is in __pycache__, venv or node_modules, which the editor leaves out of a folder anyway.
- Order. The files at the top come first, then each folder in the order of the names, a folder's own files before its folders. At the top and in each folder, its
indexfile comes first, then itsREADME, then the rest by name. Think Python's ZIP, with itsREADME.mdat the top andchapters/chap00preface.ipynbtochap19.ipynb, opens as one document: the README, then the preface and chapters 1 to 19. - A README in a folder starts with its book closed in the project's tree, and so is no chapter: in a folder it most often describes the files there, such as a
data/folder. Open its book and it is a chapter, and stays one, also for whoever opens a link to the project. - The contents. Where the chapters are in more than one folder, the contents have a caption for each folder, with its chapters under it: the first
#heading of the folder'sindexorREADMEchapter, else the folder's name made readable, so02-datareads "Data". The chapters at the top stand first, with no caption. Only the group you are reading is open; click a caption to open or shut its group. The buttons under a chapter name the group too, as "Chapters · Chapter 6". With more than 12 chapters, a field at the head of the contents keeps only the chapters and sections whose titles have what you type. - Names in a chapter. A picture, a link or a
src=file that a chapter in a folder names is a name in that folder, as Jupyter and Quarto read it:images/plot.pnginchapters/chap01.ipynbischapters/images/plot.png, and../data/scores.csvisdata/scores.csv. A name cannot climb above the top of the project. Update outputs writes a Markdown chapter's pictures beside it, in its folder. - The working folder. A cell of a chapter in a folder runs with that folder as its working directory, as Jupyter runs a notebook where it lies:
open("words.txt")inchapters/chap01.ipynbreadschapters/words.txt. The top of the project stays on Python's import path, soimport helpersfinds thehelpers.pyat the top from a chapter in any folder, and a module beside the notebook is found too. After the cell the working directory is the top of the project again, so Run, the console and a chapter at the top work there as before.
Tables of contents#
A book made with Jupyter Book or Quarto says in a file of its own which files are its chapters, in what order, and in which parts. The editor reads three of them, at the top of the project only:
| File | Made by | What it lists |
|---|---|---|
_toc.yml | Jupyter Book 1 | root, then chapters, or parts each with a caption and its chapters |
myst.yml | Jupyter Book 2 and MyST | project: toc:, entries with a file or a pattern, an entry with a title and children a part |
_quarto.yml | Quarto, for a project of type: book | book: chapters:, a part: with its chapters, and appendices |
format: jb-book
root: intro
parts:
- caption: The basics
chapters:
- file: chapters/chap01
- file: chapters/chap02
- caption: Further
chapters:
- file: chapters/chap03Where there is one, only the files it lists are chapters, in its order, and every other Markdown, Quarto, R Markdown or notebook file is an ordinary file, with a tab of its own. A file may be named without its ending, as Jupyter Book writes it. The parts are the captions of the contents; an entry listed under another entry is a chapter of the same part. A file it lists that the project does not have is left out, and the browser's console says which. A table of contents that cannot be read, or that lists no file the project has, counts as none, and the chapters are found in the folders as above, so the document never goes missing. The editor never writes one: edit it in its tab, and the document follows as you type. One in a folder is not read.
Edit, Done and ×#
The pencil on the document's tab opens the Markdown of the file the chapter you are reading is in, for editing, at that chapter (a Quarto, R Markdown or MyST file opens at its top). Change anything; a draft you have in an example stays a draft, and finds its cell again afterwards. The pencil stays pressed while you edit; pressing it again, or Ctrl/Cmd+Enter, shows the document again with your changes, which are in the file: the file in your project has the same text, and Undo takes the whole editing back as one step. On a chapter that comes from a notebook the pencil shows the notebook as MyST text, as Jupyter Book reads it: its Markdown cells as they are, each code cell a {code-cell} python block with its tags under its first line (:tags: [remove-input]), and a line +++ before each Markdown cell that follows another cell. Whatever you change there, a cell changed, added, split or removed, is written back into the notebook, which stays a notebook: a ```python block you type in a Markdown cell is its text, a {code-cell} block typed after it is a new cell, a +++ splits a Markdown cell in two and taking one out between two Markdown cells joins them, and a cell moved elsewhere in the text is the same cell. Outputs stay with code that is unchanged; a code cell whose code you changed reads Out of date until it runs again. A code cell can also be changed in place, in its frame, as a draft with its tick. While you edit, the tab also offers Update outputs (the chip), described in section 4.
The arrow at the top left of the document, with the contents' button and the switch that hides the code, downloads the document as a Jupyter notebook (.ipynb): its text as Markdown cells, its cells as code cells with what they printed and drew as their outputs, the pictures inside the file, so the notebook is one file that opens anywhere Jupyter does. It is the document as you see it, so the outputs a Quarto, R Markdown or MyST file shows after Update outputs, which that file does not keep, are in the notebook.
× on the tab closes the document, and nothing is deleted: its files stay in the project, and a click on one of them in the projects list shows it again, as opening or adding a document does.
Reloading and sharing#
A document stays open across a reload, at the chapter you were reading and where you were in it. That is kept with the project, as which tab you were on is; reading chapters is no change to your files.
A lesson from the site, opened by a link that names its address, is fetched again whenever its project opens, as long as you have not changed its file and none of its examples holds a draft: a mistake the teacher has fixed reaches you without your doing anything. Once you change the file, it is yours, and Start over is the way to the site's version.
Link to this project, in the projects list the project button opens, copies a link that carries the files that are included, the document's among them; a lesson from the site that you have not changed goes in as its address, which keeps the link short. Whoever opens it gets them in the tabs and the document beside them.
2Notebooks, R Markdown and Quarto#
Jupyter notebooks#
A Python notebook (.ipynb) opens as a document. Its markdown cells are the text, as they are. Each code cell becomes lines for the console, so the cells share their names, as they do in Jupyter. What the notebook saved under a cell is shown under it as saved output: text in an output box, a plot as a picture, and a plotly figure as the live chart it was, which you can point at and zoom. That chart is drawn by the plotly you install in Python; until you have, it says so, with a button Install plotly that installs it for you. HTML it saved, such as a data frame's table, is drawn with the same few tags the document's own HTML may use; HTML that would show nothing without its scripts, a widget's say, is shown as its text instead. Markdown and LaTeX it saved, such as a SymPy formula, are drawn with their formulas typeset.
A notebook's % lines work in its cells as they do at the console: %time, %timeit, %run, %who and the rest, and %pip install, which fetches the package when the cell runs. So do the cell commands that begin a cell with %%, such as %%time, %%writefile and %%latex, and the ones a notebook's own helper module registers, as Think Python's thinkpython.py does for %%expect. The handbook's console section lists them.
A cell's tags change how it is shown, in the words Jupyter Book and nbconvert use:
| Tag | What it does here |
|---|---|
remove-cell | The cell runs when a cell below catches up, but is not shown and has no output. If it fails, it is shown with its code |
remove-input | Only the cell's Run here is shown, not its code |
hide-input | The cell starts with its code hidden, which its chevron shows. A cell that Jupyter shows folded (Collapse selected code) counts as tagged so |
remove-output | The saved output is left out |
raises-exception | The cell ends in an error on purpose; the cells below still run |
skip-execution | The code is shown and never run |
fresh | Catching up from below stops at this cell |
console-only | Only the cell's Console button, no Run here: for lines that wait for you at every step. Console first runs the cells above that have not run yet; catching up and Update outputs pass the cell by |
A cell saved with an error as its output is taken as raises-exception too: the notebook shows the error was there when it was saved, so the cells below still run past it.
To give a cell a tag, open its chapter with the pencil and write the tag under the cell's first line, after :tags:, or behind the language on that line itself. The two are the same tag, and the next time the pencil opens the notebook, the tag stands under the line. This cell, which ends in an error on purpose:
```{code-cell} python raises-exception
int("seven")
```is the same cell as:
```{code-cell} python
:tags: [raises-exception]
int("seven")
```Several tags are separated by commas, :tags: [remove-input, raises-exception], or by spaces behind the language. Taking a tag out of the line takes it off the cell.
A document's own Markdown takes the same tags, behind its fence's language: ```python console raises-exception (see Words for code that is not run as it stands). A notebook made from the document carries them as its cells' tags, and a notebook read as a document gives them back on its fences.
Several notebooks, picked or dropped together, or a folder of them, make one document with a chapter each, in the order of their names, the notebooks in its folders too (see Chapters in folders). Each chapter is headed by the notebook's own first # heading, or its file name, and its other # headings become sections. Each notebook's cells catch up only within that notebook, as each had its own kernel in Jupyter, and as every file of a document does. A folder can also hold .md chapter files beside the notebooks; they all go in, in one order.
The other files in the folder, the modules the notebooks import and the data they read, come with the document and become tabs among your files when it opens. A notebook in another language is not run here; for R, see section 5.
Quarto and R Markdown#
A .qmd or .Rmd file opens as a document too. Each Python chunk, written ```{python} (or {python3}, or quarto-live's {pyodide}), becomes lines for the console, and the chunks share their names, as they do when Quarto renders the file. The chunk options are read from the #| lines at the top of a chunk, or from the chunk's header, as in {python echo=FALSE}, and from the defaults in the front matter's execute: or knitr: opts_chunk::
| Option | What it does here |
|---|---|
include: false | Runs when a cell below catches up, but is not shown. If it fails, it is shown with its code |
echo: false | Only Run here is shown, not the code |
code-fold: true | The chunk starts with its code hidden, which its chevron shows. In the front matter, on its own or under format: html:, it is so for every chunk |
eval: false | The code is shown and never run |
error: true | An error in the chunk does not stop the cells below |
fig-width: 8, fig-height: 5 | Its matplotlib plots are drawn that size, in inches, as Quarto sets them, and shown smaller where the page is narrower; fig-asp: 0.6 gives the height as a part of the width. knitr's fig.width=8 is the same. In the front matter, on its own, under format: html: or in knitr: opts_chunk:, it is so for every chunk. A side not given stays as it was, primopy's 6.2 by 3.7 unless the program changed it |
A knitr::opts_chunk$set(echo = FALSE) line in an R chunk changes the defaults from the next chunk on, as it does when knitting, when every value in it is written out. So is an option: echo=solution, a value that comes from a variable, is not guessed at, and the default stands. Chunk labels go.
A chunk in another language, such as {r} or {bash}, is shown as code and not run. A plain ```python fence without braces is shown and not run, as Quarto leaves it. Inline code, such as `{python} x`, stays as it is written. child=, file=, code= and ref.label= are not followed. A callout's ::: lines and a heading's {#id .class} go, and what they held stays.
The front matter's title: becomes the document's title when the text has no # heading of its own. Its params: become a hidden first cell that runs before any other, built from their default values:
params = {
"region": "north",
"year": 2024
}A value Python cannot be given the way Quarto would read it, such as an R expression or a date, is left out rather than guessed at. In a .qmd file, yes, no, on and off are the strings they look like, as Quarto reads them, and only true and false are True and False; in an .Rmd file all of them are True or False, as R Markdown reads them.
In a folder, index.qmd comes first. A README.qmd is the folder's note. An X.md beside an X.qmd is the rendered copy, and so a file rather than a chapter. With a Quarto or R Markdown chapter, the rest of the folder comes along, as with notebooks, since its code reads it.
MyST notebooks#
A .md file that is a notebook in MyST text, as jupytext --to myst writes one and Jupyter Book reads it, opens as a document like a notebook. It is one when its front matter has jupytext: or kernelspec:, or it has a ```{code-cell} block. Its Markdown is the text, and each {code-cell} becomes lines for the console, with its :tags: doing what a notebook cell's tags do (the table above). A cell in another language, and a {raw-cell}, are shown and not run, and so is a plain ```python fence. The +++ lines between cells go. The file keeps no outputs: Update outputs runs its cells, and the status line says the file keeps none. The pencil shows it as the text it is. jupytext --to myst notebook.ipynb makes one of a notebook. An X.md dropped beside an X.ipynb, as jupytext pairs them, is a file rather than a second chapter of the same notebook; its chapter toggle in the projects list is off.
Changes go back in the file's own form#
The tick on a changed cell (section 1) writes the code back into its own file, in that file's syntax, and writes outputs only where the format keeps them. A Markdown file gets the fence's lines and the text output fence under it. A notebook gets the cell's source and outputs (text as a stream, a plot as a picture), its execution_count left empty, a cell whose output is out of date marked in its metadata, and the rest of the JSON as it was, with the indent it had. A .qmd or .Rmd file gets the chunk's code lines between its header and its #| lines and its closing fence, and a MyST notebook the {code-cell}'s code lines under its options, and neither gets output, since rendering makes that. A fence that names a file with src= writes that file. No file is turned into another format. A notebook cell that carries a program's other files in its metadata cannot be changed this way.
3Writing a document#
A document is a Markdown file: headings, paragraphs, lists, tables, links, pictures and fenced code. What primopy adds is a few words on the line that opens a fence. They are the same words the handbook's pages are built from, so one Markdown file makes a page on the site and a document in the editor.
Lines for the console#
A fence marked console holds lines to type at the prompt. Each line, or each block such as a for loop, runs as if typed, and an expression shows its value, so words on its own line shows the list:
```python console fresh
words = ["tea", "bread", "apples"]
```That is the fence of this cell:
words = ["tea", "bread", "apples"]words.sort()
wordsThe word fresh makes the first cell a starting point: running the second cell catches up as far as the first and no further, so nothing from section 1 runs again. Use it where a new part of a document starts afresh. It bounds what catches up; it does not clear any names. A transcript, lines beginning with >>>, is lines for the console too, without being marked.
A program, with its files#
A fence marked python, with no console, is a program, main.py. A fence right under it that names a file with file= is another tab of the same example, a module or a data file:
```python
with open("scores.txt") as f:
scores = [int(line) for line in f]
print("Best:", max(scores))
```
```text file=scores.txt lines=4
72
88
```Here is a full one. lines=4 keeps the data file's box about four lines tall; the rest scrolls inside it.
with open("scores.txt") as f:
scores = [int(line) for line in f]
print("Best:", max(scores))
print("Average:", sum(scores) / len(scores))72
88
95
61
80
78Output:
Best: 95
Average: 79.0A program that asks with input() gets its answers from a stdin fence under it, one answer per line. Without one, it asks in the Output tab.
name = input("Your name? ")
print("Hello,", name)AdaOutput:
Your name? Ada
Hello, AdaMore words for a program's fence:
file=tools/helpers.pynames the tab; a fence that names one joins the example above it.pip=numpy,matplotlibnames packages to install when the example is run or opened.- A
%pip install richline in the code does the same, as in a notebook, and so does!pip install. The line isn't Python: when the cell runs, the packages are fetched from PyPI, and Python never sees the line. Options such as-qand--upgradeare for pip, and are left out. src=data.csvfills the fence from a file beside the Markdown, which is how a file that is not text, such as a spreadsheet, comes along:text file=book.xlsx src=book.xlsx` with the fence left empty. On a page of the site this names a file beside the page's Markdown; in a link the file travels in the link.- A
quizfence under an example carries questions for the tutor, with a Start quiz button; the handbook's section on quizzes says how to write one.
Exercises with a check#
A check fence under a program makes it an exercise. The reader fills in the code in its frame and presses Check, which runs the code as it now stands with the check fence's code after it, as one program. Each assert in the fence is a check of its own: one that fails doesn't stop the ones after it. The fence's other lines, such as one that sets up a variable, run in order between them. A fence with no check in it is one check: all of it, which passes when it runs without an error. The document doesn't show the check, and the handbook's pages and links leave it out.
```python
def square(x):
...
```
```check
assert square(3) == 9, "square(3) should be 9"
assert square(-2) == 4, "square(-2) should be 4"
```Here is that exercise, ready to check in the editor's document:
def square(x):
...Under the code, the card beside Check says how the last check went: "All 2 checks pass", or how many passed and what the first failing check says, such as "Not yet: 0 of 2 checks pass. square(3) should be 9". An assert without a message is quoted as it stands. Each failing check gets a line on the Output tab. An error in the reader's own code ends the program before the checks, and the card shows its last line, such as "Not yet: NameError: name 'y' is not defined", with the whole traceback on the Output tab, as after a Run. The checks run in the project's Python like any example, so their names are at the console afterwards.
A time limit on the fence makes an exercise weigh an algorithm as well as test it: with timelimit=200ms (or timelimit=2s), each check must finish within that time, and one that takes longer fails even when its result is right.
```check timelimit=200ms
data = list(range(100_000, 0, -1))
assert my_sort(data) == sorted(data), "my_sort() should sort 100,000 numbers"
```A selection sort fails that check with "assert my_sort(data) == sorted(data), … took 41.2 s, more than the 200 ms allowed". With a limit, the Output tab also says what each passing check took, and the card says "All 2 checks pass, each within 200 ms". Without one, nothing is timed. A slow check isn't stopped when it runs over: it runs to its end, or until Stop. Only the checks are timed, not the fence's other lines or the reader's own code before them.
The check is hidden, not secret: it is in the Markdown, where Edit shows it. An exercise's code isn't folded away, and Open and Run here take the code without the check.
What to watch in a recording#
A watch fence under a program says what to look for while stepping through its recording. The document shows its notes under the example, as plain text. With one, the example gets a Watch button, which records it and plays it back right there, and Open records it as it opens: the editor, the execution tape, the call stack and the variables take the screen. Either way, each note appears above the tape while the tape stands on its line.
total = 0
for s in [72, 88, 95]:
total += s
print(total)What to watch
- Nothing has run yet. The next line makes
total. - The first pass:
sis 72, andtotalis about to become 72. - Another pass:
totalgrows bys. - The last pass. What will
printshow? - The loop is over, and
sstill holds the last score.
Each line of the fence starts with the line of code it is about, then a colon and the note. In square brackets after the line number, Python's indexes and slices pick the times that line runs, counted from 0:
3is every time line 3 runs.3[0]is the first time,3[1]the second, and3[-1]the last.3[1:]is every time after the first,3[:2]the first two, and3[::2]every other one.helpers.py:3[0]is about a line of another tab of the example.
A line of the fence that starts with no line number goes on with the note above it, and a word in backticks is shown as code. vars= names the variables to watch: they come first and are marked, in Watch's player and in the Variables pane. The player always shows the global variables, but not functions, classes and modules unless vars= names them, as square in vars=total,n,square. A function's local variable is named with its function, as in vars=total,n,square.x, and shows while that function runs. The bars with a note get a mark on top of the tape, so you can find them. A note is about the line the tape stands on, which is the line about to run.
The notes hold for the example as it is written: once its code is changed, line 3 may be another line, and the notes are no longer shown. A program fence marked record, such as python record`, gets Watch too, and is recorded when it is opened, with no notes.
Words for code that is not run as it stands#
These are the tags of a notebook's cells (the table under the notebooks above), written behind the fence's language. A Quarto or R Markdown file's chunk options become them too:
| On the fence line | What the reader gets |
|---|---|
python console remove-cell | Nothing on screen. The lines run when a cell below catches up, and appear with their code only if they fail. Good for imports and setup |
python console remove-input | Only Run here, with the caption code hidden |
python console hide-input | The cell with its code hidden at first: its title bar, with its buttons, and a chevron that shows the code |
python skip-execution | The code, with no button that runs it, and catching up passes it by |
python console console-only | Lines for the console only: the Console button runs the cells above that have not run yet and puts the lines there, and there is no Run here. Catching up and Update outputs pass them by |
python console raises-exception | Lines that end in an error on purpose. Catching up counts them as run and goes on |
The shorter words earlier documents used, hidden, nocode, norun and error, still work and mean the same.
A skip-execution fence, for code that must not run here:
while True:
print("for ever")A raises-exception cell, which catching up goes past:
int("seven")And a remove-input cell, which shows only its button:
Saved output#
What a cell printed can be kept under it, as a notebook keeps it: its text in a fence marked text output, and each plot or drawing as a picture named out-N.png on a line of its own, where N counts the document's cells that run, program examples included, from the top. Here the cell is the document's third:
```python console
print(6 * 7)
```
```text output
42
```
A plotly figure is kept the same way, as the figure itself in a file named out-N.plotly.json, , and the document draws it again as a live chart, as a notebook's saved figure is (see Jupyter notebooks). Other readers of the Markdown, such as GitHub, show only the word Output there.
HTML a cell showed, such as a table, is kept in a fence marked html output. The document draws it with the same few tags its Markdown may use (see Headings, links and pictures), a table's cells right-aligned, as Jupyter draws them; what a <style> or <script> holds is left out, and so are its classes and styles. A notebook made from the document keeps it as text/html. Markdown a cell showed, with Markdown(...) or %%markdown, is kept in a fence marked markdown output, and LaTeX, from %%latex, Latex(...) or a SymPy formula, in one marked latex output. Both are drawn as the Display tab draws them, the formulas typeset, and a notebook keeps them as text/markdown and text/latex. A notebook you open that saved such outputs shows them the same way.
Only what stands directly under a cell in exactly this form, with blank lines between, counts as its output. A plain text fence of your own, or a picture of another name, is left alone. You need not write saved output by hand: Update outputs writes it, see the next section.
Headings, links and pictures#
Each # heading starts a chapter; each ## heading is a section, listed under its chapter in the contents. ### and below are not listed. Every heading has an anchor, its text in lower case with spaces as - and punctuation left out, as on GitHub: ## 3. Writing a document is #3-writing-a-document. A link to it, [Writing](#3-writing-a-document), goes to it in whichever chapter it stands. A link that opens a document at a heading adds &ch= and the anchor: #mdu=/handbook/documents.md&ch=saved-output.
- A link to another
.mdfile beside a document of the site, such as[the drawing reference](./draw.md), opens that document on the tab; on a page of the site it goes to the page built from it: the drawing reference. Any other page of the site opens in a new browser tab. - In a folder of chapters, a link to another chapter file,
[next](02-loops.md#while), goes to that chapter, and so does one into another folder,[part two](../part2/intro.md). - A link to a web page opens in a new tab, with the name of its site written after it, so you can see where it goes.
- A picture shows when it travels with the document, or is a file of the site beside a document of the site. A picture on another server is not fetched, since fetching it would tell that server who is reading.
- A picture of an SVG,
, is a still picture. To have one that moves and answers the mouse, write it in a fence markedsvg live, or a whole web page in one markedhtml live, or name the file withsrc=and leave the fence empty:html live src=demo.html`. In the document tab it runs by itself once you scroll near it, in a frame of its own, as tall as it is, with its scripts, hovers and animations, and nothing in it can reach the editor, your projects or your browser's storage, or fetch anything from the web. The pages of the site show its source. - In the document tab,
$x^2$is a formula, and$$…$$on lines of their own a formula set apart. As in Jupyter,\begin{…}…\end{…}and\[…\]on lines of their own are one too. So is amathfence, as GitHub writes one, and MyST's{math}. The pages of the site do not render them. - In the document tab, the HTML that notebooks use for text is drawn:
<b>,<i>,<u>,<sub>,<sup>,<br>,<hr>,<center>,<p>and<div>aligned,<details>with its<summary>, tables with their cells aligned and spanned,<font>with a colour and size, a<span>with a colour, links (<a href>) and anchors to link to (<a id>), and pictures (<img>) aligned and sized, the links and pictures by the same rules as Markdown's. Any other attribute is left out, any other HTML is shown as text, and comments are not shown. Markdown and formulas in the lines right under a tag that stands on a line of its own are shown as written; leave a blank line after the tag to have them drawn.
A live fence marked themed as well, html live themed, holds only what goes in the page's body: its elements, a<style>of its own if it needs one, and its scripts, with no<head>`. The document gives it the editor's look: the editor's fonts as near as the frame can have them, quiet styles for its text, buttons, inputs, code and tables, and the editor's colours by name, which follow the editor's light or dark theme as it changes, without the page starting again, so a reader's place in it stays. The names are custom properties, and a style of the page's own always wins over the document's:
| Name | What it is for |
|---|---|
--bg, --fg | The page, and its text |
--dim | Quieter text, such as a label |
--rule | Lines and borders |
--panel | A box set off from the page |
--blue-fill | A fill that white text reads on, such as a main button's |
--blue, --amber, --green, --red | Lines, marks and text in that colour, which read on the page |
--blue-tint, --amber-tint, --green-tint, --red-tint | A box filled in that colour, with --fg on it |
--c1 to --c6 | The series of a plot, in that order |
--sans, --mono | The fonts |
In a style they are written var(--dim), in an <svg> as a style too, style="fill: var(--c1)". A script that draws with colours of its own asks for one with primo.color('fg'), which gives the colour as it is now, such as #182031, and draws again when the theme changes, on the primotheme event: addEventListener('primotheme', draw). primo.dark says whether the editor is dark. Opened anywhere else, such a page has none of this, and is drawn in the browser's own colours; where it should read well there too, give each name its light value as well, var(--fg, #182031), and in a script window.primo ? primo.color('fg') : '#182031'.
<p>Pressed <b id="n">0</b> times.</p>
<button id="press">Press</button>
<p><svg viewBox="0 0 200 24" width="200" height="24"><rect id="bar" x="0" y="4" width="0" height="16" rx="4"/></svg></p>
<script>
let n = 0;
const bar = document.getElementById('bar');
function draw(){
bar.setAttribute('fill', primo.color('c1'));
bar.setAttribute('width', Math.min(200, n * 20));
}
document.getElementById('press').onclick = () => {
n++;
document.getElementById('n').textContent = n;
draw();
};
addEventListener('primotheme', draw);
draw();
</script>Editing a document with Claude#
Claude, or another assistant that speaks MCP, can work on a document in the editor while you watch: read its chapters, change them, add one, run its cells and update its outputs. It works on the project you have open, in your browser; nothing is uploaded but what Claude reads and writes.
- Connect the editor. Open the projects list with the project button beside the logo and press Connect to Claude. The first time, you sign in, with the account the tutor uses. The line beside the button then says it is connected.
- Add the connector to Claude, once. In Claude, add
https://mcp.primopy.com/mcpas a custom connector (in claude.ai under Settings → Connectors; in Claude Code withclaude mcp add --transport http primopy https://mcp.primopy.com/mcp), and sign in there with the same account. That pairs the two: Claude's tools act in the tab you connected. - Ask. "Add a chapter on dictionaries with three exercises", "the second example in loops.md fails, fix it", "update the outputs of notes.md". Claude looks first at what is open, so "this chapter" and "the selected paragraph" mean what you are looking at; text you select in the document view counts as the selection.
What it does goes through the editor's own ways, so you see every change and can take it back:
- An edit to a document file is one step of Undo in that file, and the status line names the file Claude changed. The document view shows the new text at once.
- A new
.mdfile, at the top of the project or in a folder, becomes a chapter of the document, in its place by the order of the names, as one you added would; where a table of contents lists the chapters, only once it is listed there. - Update outputs runs the file's cells from a fresh start and saves their outputs under them, as the chip of that name does (see Update outputs); Undo takes it back as one step.
- Show a file brings a chapter to the front, for you to read what Claude is talking about.
Claude reads and writes a file's text as it is kept: a Markdown file as Markdown, a notebook as its JSON. Only one tab writes a project; if the same project is open in a second tab, the one that only shows it refuses changes, and Claude is told to work in the other. Disconnect, in the same place, ends it; a reload of a connected tab connects it again.
Read what Claude wrote before you hand it out. Run every example once, or press Update outputs: a cell that fails says so there, not in front of a class.
4Update outputs, and getting a document out#
Update outputs#
Open the document with the pencil on its tab, and Update outputs, a chip, appears beside it. Pressed, it takes the drafts in your cells into the files, as the tick would (the outputs from the first changed cell on read Out of date until the update reaches them), and writes the saved output of every cell of the file you are editing afresh, the file of the chapter on show:
- It clears the console's names, as Run does.
- It runs every cell of that file from its top, in order: console lines, hidden cells and program examples alike. Each one's output appears in the tabs below as it runs, and while it runs, the chip is a square, Stop.
- Under each cell it writes what that cell printed, as a
text outputfence, and its plots, displays and drawings as pictures named<file>_files/out-N.pngamong your files (out-N.svgfor a chart drawn as SVG, as charts are unless you chose otherwise,out-N.webpfor one made WebP) (aplotlyfigure as<file>_files/out-N.plotly.json), in place of what was saved there before. A Markdown file keeps outputs under its cells and a notebook in its cells' outputs, aplotlyfigure asapplication/vnd.plotly.v1+json, as Jupyter keeps it; the cells of a Quarto, R Markdown or MyST file run all the same, and since such a file keeps no outputs (rendering it makes them), they are shown under its cells without being written into it, to read the document with its results or print it from the browser; they stay until the file changes, the page is reloaded or you update again, and the status line says so. The document's other files are neither run nor written; update each on its own. Undo takes the whole update back.
A program example gets a text output fence too. An Output: line with a plain text fence of your own under a program stays as it is, so in a document you mean to update, leave it out, or the output is there twice. A hidden cell runs, but gets no output written, and anything saved under it goes. A transcript keeps the output it was written with. A skip-execution fence is no cell at all. Very long output is cut after 2000 lines or 100,000 characters, with a line saying so.
When a cell ends in an error, the update stops there and the status line names the cell; its error is written as its output, with the outputs of the cells above it. A cell marked raises-exception is the exception: its error is its output, and the update goes on. Stop stops the update too, and keeps what the cells before it wrote. The document is then kept as an edit is: Undo brings back the one before while the tab stays open, and a reload or a link carries the new outputs, pictures included.
Remove outputs#
Beside the chip, while you edit, is the same chip struck through: Remove outputs. It takes the saved output of every cell of the same file out of it: the text output fences and pictures under its cells (a picture that the text shows elsewhere stays), the Out of date marks, and in a notebook its cells' outputs. The code and the text stay as they were. The file gets smaller, and so does a link to the project; whoever opens it runs the cells to see their output again. Undo brings the outputs back. A Quarto, R Markdown or MyST file keeps no outputs, so there are none to take out.
Outputs made again on opening#
In the projects list's Included column, a Markdown file's or a notebook's row has a second button after its tick box: a code cell over a chart, while Download and the link take the file's outputs as they are. Click it and the chart gives way to an arrow from the code cell round to an empty chart: Download and the link then leave that file's outputs out, with the pictures only they showed, which keeps the link short. They also say that the outputs are to be made again. Whoever opens the link, or drops the ZIP onto the editor, has that file's cells run as soon as the language is up, as Update outputs runs them, and their outputs saved; a project made from a link still counts as unchanged. The setting stays with the project, and travels with it.
Download#
Download, over the files' tick boxes in the projects list, saves the files that are included in a ZIP, the document's among them; drag that ZIP onto the editor and the project comes back, document and all. A document file whose book is closed is still a file of the project, still in the ZIP, and is no chapter. Chosen with From files or a ZIP… in the projects list, the ZIP comes back as a project of its own.
Making the link yourself#
The quickest way is the editor itself: open the notebook, file or folder, then Link to this project in the projects list. That link carries every file that is included, so untick the ones your students should not get before you copy it.
A teacher who has primopy_link.py, the script primopy's own pages are built with, can make the link at a shell instead, without a browser:
python3 primopy_link.py --doc notes.md
python3 primopy_link.py --doc course/
python3 primopy_link.py --doc lesson.ipynb
python3 primopy_link.py --doc lesson.qmd
python3 primopy_link.py --doc course.zip
python3 primopy_link.py --doc notes.md --attach helpers.py --attach data/--doc takes one Markdown, notebook, Quarto or R Markdown file, or a folder or zip of them, and reads it exactly as a drop on the editor would, except a MyST notebook, which it reads as plain Markdown and says so; a ZIP of that folder reads back as the document it was. --attach adds a file or a folder that the Markdown does not name but its code needs; a link.json beside the Markdown can list them instead, as {"attach": ["helpers.py", "data/"]}. --chapter opens the link at a heading, by its anchor. --base says where the editor lives, if not at https://primopy.com/ide/. The tool prints the link.
A link holds at most 400,000 characters and carries at most 100 files. What it unpacks to may be far more, since text that repeats packs small, and it opens whole. A link past those limits is an error, said at the shell, rather than a link that opens short. A notebook over 4 MB, or a zip that unpacks to more, is not read, as a drop does not read it, and a file over 400 KB in a folder of notebooks is left out, as a drop leaves it out; the tool says so. For anything larger, put the Markdown on a site and link to it, or hand out the ZIP.
Links in a mail or on a slide#
A short link goes anywhere. A long one, a document with its pictures or a project with several files, does not survive everywhere: Exchange (Outlook) cuts a long link in the text of a mail, and PowerPoint cuts an ordinary link, so the link that arrives opens nothing. Each has a way round:
- In a mail, put the link in a file and attach it, such as a short document or the slides that hold it: Exchange leaves an attachment as it is. Or send the way to the link, the Moodle course or the Teams channel below, where the whole link is kept.
- In PowerPoint, an ordinary link, put on text or a picture with Insert → Link, holds only about 1,000 to 2,000 characters, and a longer one is cut. So rather link the slide to the Moodle course or the Teams channel below, a short address that holds the long link for you, and that you can change later without touching the slides. Only an action button keeps a long link whole: Insert → Shapes → Action Buttons, draw the button, and in Action Settings, on Mouse Click, choose Hyperlink to: → URL… and paste the link. A click on the button in the slide show opens it whole. To hand out the slides as a PDF, export them with Microsoft's online service (on a Mac, File → Export → PDF, Best for electronic distribution and accessibility): PowerPoint's local PDF export drops everything from the
#on, so the link in the PDF opens the editor without the project. Keynote and LibreOffice (or OpenOffice) keep the whole link when they export the slides as a PDF.
A slide made with LaTeX keeps the whole link. In Beamer, put it behind a few words with \href; the # before the link's data is written \#, and the frame is fragile, so that the link's other characters reach the PDF as they are:
\usepackage{hyperref} % in the preamble; Beamer loads it already
\begin{frame}[fragile]{Lesson 3: loops}
Try it yourself:
\href{https://primopy.com/ide/\#mdz=…}{open the exercise in primopy}
\end{frame}Paste the link from Link to this project, or from primopy_link.py --doc notes.md, in place of https://primopy.com/ide/\#mdz=…, and put the \ before its #. A PDF viewer opens the link in the browser when the words are clicked. TeX reads a line of at most 200,000 characters by default, so a link longer than that stops pdflatex with Unable to read an entire line: shorten it as below, or hand out the ZIP.
Putting a link on Moodle or Teams#
A link carries the whole document in the address, so Moodle or Teams only has to hold the address. Nothing goes to a server, and nothing comes back either: each student gets a copy of their own in their own browser, and their work is not handed in or graded through it.
Either way has one more advantage: the link stays yours to edit after you have published it. Find a mistake in the lesson, add an exercise, or bring the outputs up to date, then copy a new link with Link to this project and paste it in place of the old one, in the Moodle resource's settings or in your Teams message. Students keep the same place to click, the course page or the channel, and whoever opens it from then on gets the new version. No file has to be uploaded again, and no new announcement is needed.
On Moodle:
- As a link in a course section. Turn editing on, then Add an activity or resource → URL. Paste the link from Link to this project (or from
primopy_link.py --doc) into External URL, and give it a name such as "Lesson 3: loops". Under Appearance, set Display to New window or Open. Embed shows nothing: the editor refuses to run inside another site's frame. To change the link later, open the resource's Edit settings and paste the new one into External URL. - As a link in text. On a Page, in a Text and media area, a section's summary, an assignment's description or a forum post, select a few words, press the editor's link button, and paste the link as its address. Let it open in a new window. To change it later, edit the text, select the words and paste the new address into the link button's field.
On Teams:
- In a channel or a chat. Write the message, select a few words such as "Lesson 3: loops", press Insert link (Ctrl+K, Cmd+K on a Mac) and paste the link as its address. Pin the message, or post it in a channel for the course, so it is easy to find again. To change the link later, open the message's ⋯ → Edit, and put the new address in place of the old one.
- Not as a Website tab. A tab shows a site inside Teams, in a frame, and the editor does not run in another site's frame, so the tab stays empty. Put the link in a message instead, where it opens in the browser.
Check it once. Save or send, then open the link as a student would, best in a private window. A long link that a field, a filter or a message cut short opens nothing: the status line says That link could not be read: it may have been cut short. Teams keeps a message to about 28 KB, so a link with a large document or many files may not fit at all. Shorten it (untick files your students do not need, or Remove outputs and let them be made again on opening), or hand out the ZIP from Download instead (a File resource on Moodle, a file in the channel on Teams), which students drop on the editor.
5Code in the other language#
primopy runs Python. Its sister, Rprimo, is the same editor for R, in the browser the same way. Drop an R notebook, a .qmd or .Rmd file whose chunks are all R, .R files, or a folder or zip of those on primopy, and nothing is added. A dialog says what it is and offers it to Rprimo instead:
- Open in Rprimo opens it there in a new browser tab, with a link that carries it. Nothing here changes.
- Copy link copies that link, to send or to open later.
- Cancel leaves everything as it was.
When it is too big for a link, the dialog offers Download ZIP instead: drop the ZIP on Rprimo's project button to open it there. Where R and Python come together, as in a .qmd with chunks of both, the drop opens here as usual, and the R chunks are shown as code. Rprimo does the same the other way round, offering Python to primopy.