# Reference

## Commands

### `sortes init`

```bash
sortes init <course>
```

Creates the folder `<course>` with `bank.typ`, an example bank, and `typst.toml`, which marks the course folder as the Typst project root.
Files that already exist are left as they are.
It also installs the sortes Typst package as `@local/sortes:0.1.0`, in Typst's package folder (or `$TYPST_PACKAGE_PATH`).
Every command checks the installed package and updates it to match the binary.

### `sortes term`

```bash
sortes term <term>
```

Creates the term folder `<term>` with an empty `sortes.lock`.
The folder must sit next to the course's `bank.typ`, so run it inside the course folder (or pass `<course>/<term>`).
The course's first term also gets an example exam, `midterm.typ`.

### `sortes build`

```bash
sortes build <exam.typ> [--redraw] [--seed N]
```

Draws the exam's questions if it has none yet, writes them to the term's `sortes.lock`, and renders the PDFs into `<term>/PDFs/`:

| Versions | Print copies                     | Solutions                                |
| -------- | -------------------------------- | ---------------------------------------- |
| 1        | `midterm.pdf`                    | `midterm-sol.pdf`                        |
| 2 or more | `midterm-A.pdf`, `midterm-B.pdf`, … | `midterm-A-sol.pdf`, `midterm-B-sol.pdf`, … |

| Flag       | Description                                                                                       |
| ---------- | ------------------------------------------------------------------------------------------------- |
| `--redraw` | Throw away the exam's draw and draw again. Not allowed once the exam is given.                    |
| `--seed N` | Seed for a new draw. Without it, a draw uses the exam's `seed:` or a random one. The seed is saved in the lock. Once the exam is drawn, use it with `--redraw`. |

Typst runs with the course folder as `--root`: the nearest folder up from the exam with a `typst.toml` (or a `.git`).
`sortes` needs `typst` on your `PATH`.
Set `SORTES_TYPST` to use a different binary.

## Bank

### `q`

```typst
#q(<id>, kind: none, points: none, cols: 1, shuffle: true)[
  Stem.
  - Choice
  - #correct[Right choice]
  #why[Explanation.]
]

#q(<id>)[
  Stem.
  #blank(expect: [a *number*])[Model answer]
]

#q(<id>)[
  Stem.
  #answer(height: 4cm)[Model answer]
]
```

The first argument is the question's ID, written as a label.
IDs are unique in the bank and permanent; see [what the next build does](#what-the-next-build-does).

A question is answered in one of three forms:

- **Choices:** the `-` list that ends the question, 2 to 5 of them. A list followed by more text belongs to the stem. With one `#correct` choice the question is single-answer; with several, multi-select (drawn with square boxes).
- **One line:** a `#blank`.
- **A box:** an `#answer`, or nothing at all.

A question with two forms, like choices and a `#blank`, stops the build.

| Option    | Default | Example            | Description                                                                                          |
| --------- | ------- | ------------------ | ---------------------------------------------------------------------------------------------------- |
| `kind`    | none    | `kind: "compute"`  | Any name. `#draw(..., min: (compute: 1))` asks for at least that many questions of a kind.             |
| `points`  | none    | `points: 4`        | The question's points. Without it, the question shares what's left of the exam's `points:`.          |
| `cols`    | `1`     | `cols: 2`          | Columns for the choices.                                                                             |
| `shuffle` | `true`  | `shuffle: false`   | Shuffle the choices in each version. Use `false` for choices like "All of the above".                |

Only single-answer questions with shuffled choices count toward the balanced answer letters.

### `correct`, `why`, `blank`, `answer`

`#correct[...]` wraps a right choice.
`#why[...]` is an explanation, shown under the question in the solutions.
`blank`, `answer` and `why` go on their own line in the question, outside the list items.

```typst
#blank(expect: none)[Model answer]
#answer(height: 4cm)[Model answer]
```

`#blank[...]` makes a one-line question. The print copy has a line labelled "Answer (on ONE line):"; the solutions show the model answer on it.

| Option   | Default | Example                 | Description                                                                 |
| -------- | ------- | ----------------------- | --------------------------------------------------------------------------- |
| `expect` | none    | `expect: [a *number*]`  | What to write, shown in the label: "Answer (a **number** on ONE line):".    |

`#answer[...]` makes a question answered in a box. The solutions show the model answer in the box, which fits its contents.

| Option   | Default | Example        | Description                                 |
| -------- | ------- | -------------- | ------------------------------------------- |
| `height` | `4cm`   | `height: 6cm`  | Height of the answer box in the print copy. |

### Sections

A heading with a label starts a section: `= Regression <regression>`.
A question belongs to the last heading above it.
Questions under a heading without a label can only be picked.

## Exam

### `sortes.with`

```typst
#show: sortes.with(
  bank: include "../bank.typ",
  lock: json("sortes.lock"),
  title: "Midterm",
  date: "2027-02-26",
  versions: 4,
  points: 100,
)
```

| Parameter  | Default      | Example                    | Description                                                                                                              |
| ---------- | ------------ | -------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `bank`     | required     | `include "../bank.typ"`    | The bank, passed with `include`.                                                                                         |
| `lock`     | none         | `json("sortes.lock")`      | The term's lock, passed with `json`. Without it, drawn questions show as placeholders.                                   |
| `title`    | none         | `"Midterm"`                | The exam's name. Not printed; `summary()` returns it. Give exams with the same draws different titles so previews can tell them apart. |
| `date`     | none         | `"2027-02-26"`             | The day of the exam, as `"YYYY-MM-DD"` or a `datetime`. After it, the exam is given.                                     |
| `versions` | `1`          | `4`                        | Number of versions, 1 to 26, named A, B, C, …                                                                            |
| `points`   | none         | `100`                      | The exam's total. Questions without `points:` share what's left, in half-point steps.                                    |
| `repeats`  | `10%`        | `20%`                      | How much of the exam may be expected to repeat from past terms. See [repeats from past terms](#repeats-from-past-terms). |
| `choices`  | `"lettered"` | `"bubbled"`                | `"lettered"` prints A–E in the bubbles, for bubble sheets. `"bubbled"` prints empty bubbles.                             |
| `seed`     | none         | `42`                       | Seed for a new draw, if `--seed` isn't given.                                                                            |
| `max-run`  | `3`          | `2`                        | The most times the same answer letter may appear in a row in a version.                                                  |

### `draw`

```typst
#draw(<regression>, 5)
#draw(<regression>, 5, min: (compute: 2, proof: 1))
```

Takes `n` questions from a section that no other exam of this term has.
`min` asks for at least that many questions of each kind.
Each version shuffles the order of the drawn questions.

### `pick`

```typst
#pick(<supervised-def>, <normal-eq-derive>)
```

Puts these questions in the exam, in this order.
A picked question that another exam of this term also has gets a note in the build output.

### `version`

`version()` is the version being rendered: `"A"`, `"B"`, ….
It is `"A"` in a preview.

### `solution`

`solution()` is `true` in the solution copy.
It is `true` in a preview, and `false` with `typst compile --input mode=print`.

### `summary`

`summary()` describes the exam, for covers and section headers.
Call it inside `context`:

```typst
#context {
  let s = summary()
  [#s.questions questions, #s.points points]
}
```

It returns:

```typst
(
  title: "Midterm",
  date: "2027-02-26",
  versions: 4,
  questions: 40,
  points: 100,
  sections: (
    (heading: [Regression], label: <regression>, questions: 8, points: 20),
    ..
  ),
)
```

`sections` has one entry per heading of the exam file that has questions under it.
`label` is the heading's label, or none.
Points are none until the first build, and when no question has points.

## Folders

```text
exams/                  the course
├── bank.typ            the question bank
├── typst.toml          marks the Typst project root
├── F2026/              a term
│   ├── midterm.typ
│   ├── final.typ
│   ├── sortes.lock
│   └── PDFs/
└── W2027/              a later term
    ├── midterm.typ
    ├── sortes.lock
    └── PDFs/
```

A term is any folder next to `bank.typ` with a `sortes.lock`.
Terms are ordered by the dates of their exams (or, for exams without `date:`, when they were first drawn), not by name.

### `sortes.lock`

The lock is JSON, with one entry per exam, named after the exam's file.
An entry holds the exam's date, title and seed, its `#draw` and `#pick` calls, the questions each one got, every question's points, each version's question order and choice orders, and the answer key.
It also keeps a fingerprint of each drawn question's text, to follow later edits.

Typst reads the lock to render the exam, and `sortes build` reads the locks of all terms to know which questions are used.
Commit it with the exams, and don't edit it by hand.

## Repeats from past terms

Within a term, exams never share a question.
Questions used in past terms, the other term folders, may come back, but `repeats:` limits how many.
The expected number of questions that repeat from past terms must stay under `repeats` times the exam's number of questions.
For 40 questions and the default 10%, that's 4.

The number is expected because the draw is random.
If 5 of the 50 questions a `#draw` can take were used in past terms, a draw of 10 is expected to repeat 10 × 5 / 50 = 1 of them.
Only drawn questions count; picked ones don't.

The build draws from every question not used this term.
If the expected repeats are over the limit, it avoids the newest past exam's questions and draws again, then also the next newest, and so on, until the expected repeats fit.
If even avoiding every past exam leaves too few questions, the rest come from the avoided ones, oldest term first, and the build warns.
Past terms are ordered by their dates, as in [Folders](#folders).

A big bank. A section has 100 questions, last term's exam used 5 of them, and this exam draws 10.
The expected repeats are 10 × 5 / 100 = 0.5, under the limit of 1, so nothing is avoided.
Each of last term's 5 questions may come up, but rarely:

```text
  ✔ 0.5 expected repeats from past terms
```

A bank that runs out. A section has 30 questions, and each term's exam draws 10:

| Term  | Draws               | Why                                                    |
| ----- | ------------------- | ------------------------------------------------------ |
| F2025 | 10 new              | There's no past term.                                  |
| F2026 | 10 new              | F2025's questions are avoided.                         |
| W2027 | The last 10 new     | F2026's and F2025's questions are avoided.             |
| F2027 | F2025's 10 again    | All 30 are used, so the oldest come back, with a warning. |

## What the next build does

These tables are for exams in the current term.
Exams in past terms don't change, see the end of this section.

Before the exam's date:

| Edit                                         | Next build                                                                                                             |
| -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| Fix a stem                                   | Renders the fix.                                                                                                       |
| Fix a choice's text                          | Renders the fix and keeps the printed choice order. A choice rewritten in entirely new words counts as removed and added. |
| Move `#correct`, add or remove a choice      | Keeps the printed order as far as it can. A removed choice closes its gap; a new one goes last. Reports the new key.   |
| Change a question's `points:`                | Splits the exam's points again and reports the changed points.                                                         |
| Delete a drawn question                      | Draws a replacement from the same section, in the same place, with the same answer letter where it fits.               |
| Delete a picked question                     | Stops: there's no such question in the bank.                                                                           |
| Change a question's ID                       | A new ID is a new question. If the old one was used and the text is the same, the build stops.                         |
| Add questions to the bank                    | Nothing: existing draws stay.                                                                                          |
| Change `n` or `min` of a `#draw`             | Keeps the questions that still fit and draws the difference.                                                           |
| Rename a section's label                     | Keeps the draw, if all its questions are in the renamed section.                                                       |
| Add a `#draw`                                | Draws it; the other draws stay.                                                                                        |
| Change `versions`                            | Keeps the existing versions and adds or drops versions at the end.                                                     |
| Rename the exam file                         | A new exam with a new draw. The old entry stays in the lock, and its questions stay used.                              |
| `--redraw`                                   | Draws everything again.                                                                                                |

Reports compare question numbers, per version.
After a new question moves the others down, later numbers show as changed too.

After the exam's date, the exam is given:

| Edit                           | Next build                                                                                                    |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------- |
| Fix the bank                   | Keeps the printed questions and choice order, reports the key for the printed paper, re-renders the solutions. |
| Delete a question from the bank | The solutions show a note with the question's answer on the paper, and the build lists it.                   |
| Edit the exam file             | The recorded questions stay. Only the solution PDFs are rendered again.                                       |
| Change a `#draw` or `#pick`    | Stops: the paper has the recorded questions. Undo the change, or copy the file to a new name.                 |
| Change `versions`              | Stops: the paper has the recorded versions. Undo the change, or copy the file to a new name.                  |
| Change `date:` to a later day  | If the new day is today or later, the exam is upcoming again. It keeps its draw, and the build renders all PDFs. |
| `--redraw`                     | Stops: a given exam can't be drawn again. Copy the file to a new name instead.                                |

Once a newer term starts, the earlier terms are frozen.
Building one of their exams changes nothing and renders nothing, whatever its date or file says.
A new exam in a past term stops the build.
So finish regrades before you start the next term.
