SelfscribeDownloadOpen the app

Code snippets

One task in many languages, with highlighting, line numbers, tabs and marked lines.

Document · Simple · uses code

Edit it in the playgroundRead the file

What it shows

Show code in any language, with line numbers, marked lines, file names and tabs.

What you learn

A language name after the fence for colours, title=NAME for a file name, lines for line numbers, {7-8} to mark lines, tabs to show one task in several languages, a diff, callout boxes.

Try this

  • Change {7-8} on the Python fence to {11}, and only the print line stays marked.
  • Change rust on the Rust fence to text, and the colours go while the file name stays.
examples/code-cookbook.self · 245 lines
~~~ selfscribe
# Lesson: Show code in any language, with line numbers, marked lines, file names and tabs.
# You learn: a language name after the fence for colours, `title=NAME` for a file name, `lines` for line numbers, `{7-8}` to mark lines, tabs to show one task in several languages, a diff, callout boxes.
# Try this: change `{7-8}` on the Python fence to `{11}`, and only the print line stays marked.
# Try this: change `rust` on the Rust fence to `text`, and the colours go while the file name stays.
# summary: One task in many languages, with highlighting, line numbers, tabs and marked lines.
# category: diagrams
# tags: document, simple, work
# uses: code
use markdown
set title Code snippets
set style sans
set heading-font Space Grotesk

# ---- "::: tab Name" ... ":::": one tab; tabs next to each other become one set --------
# group div gathers neighbouring tabs into one box, so a reader picks a language at the top.
block  ::: tab _ ... :::  -> tab label=_1  group div

# ---- "::: kind Title" ... ":::": a callout box, such as tip, note or warning ----------
# The first word picks the kind and its colour; the rest of the line is the box's title.
# This rule is shorter than the tab rule, so "::: tab" still makes a tab.
block  ::: _ ... :::      -> callout kind=_1

# ---- "lead …" under the title: a larger opening line ------------------------------------
line   lead _             -> p.lead  { font-size: 1.12em; line-height: 1.5; opacity: 0.8 }  as cc-lead
~~~
# Total orders per customer

lead Read a file of orders, add up each customer's amounts, and print the biggest first. The same small job in eight languages.

::: tab Python
```python title=totals.py lines {7-8}
import csv
from collections import defaultdict
from decimal import Decimal

totals = defaultdict(Decimal)
with open("orders.csv", newline="") as f:
    for row in csv.DictReader(f):
        totals[row["customer"]] += Decimal(row["amount"])

for customer, total in sorted(totals.items(), key=lambda t: -t[1]):
    print(f"{customer:<15} {total:>8.2f}")
```
:::
::: tab TypeScript
```ts title=totals.ts lines {6-10}
import { readFileSync } from "node:fs";

const rows = readFileSync("orders.csv", "utf8").trim().split("\n").slice(1);
const totals = new Map<string, number>();

for (const row of rows) {
  const [customer, amount] = row.split(",");
  const cents = Math.round(Number(amount) * 100);
  totals.set(customer, (totals.get(customer) ?? 0) + cents);
}

for (const [customer, cents] of [...totals].sort((a, b) => b[1] - a[1])) {
  console.log(customer.padEnd(15), (cents / 100).toFixed(2).padStart(8));
}
```
:::
::: tab Rust
```rust title=src/main.rs lines {7-11}
use std::collections::HashMap;
use std::fs;

fn main() {
    let text = fs::read_to_string("orders.csv").expect("orders.csv");
    let mut totals: HashMap<&str, i64> = HashMap::new();
    for line in text.lines().skip(1) {
        let (customer, amount) = line.split_once(',').unwrap();
        let cents = (amount.parse::<f64>().unwrap() * 100.0).round() as i64;
        *totals.entry(customer).or_default() += cents;
    }
    let mut rows: Vec<_> = totals.into_iter().collect();
    rows.sort_by(|a, b| b.1.cmp(&a.1));
    for (customer, cents) in rows {
        println!("{customer:<15} {:>8.2}", cents as f64 / 100.0);
    }
}
```
:::
::: tab Go
```go title=main.go lines {17-21}
package main

import (
	"encoding/csv"
	"fmt"
	"os"
	"sort"
	"strconv"
)

func main() {
	f, err := os.Open("orders.csv")
	if err != nil {
		panic(err)
	}
	rows, _ := csv.NewReader(f).ReadAll()
	totals := map[string]float64{}
	for _, r := range rows[1:] {
		amount, _ := strconv.ParseFloat(r[1], 64)
		totals[r[0]] += amount
	}
	names := make([]string, 0, len(totals))
	for name := range totals {
		names = append(names, name)
	}
	sort.Slice(names, func(i, j int) bool {
		return totals[names[i]] > totals[names[j]]
	})
	for _, name := range names {
		fmt.Printf("%-15s %8.2f\n", name, totals[name])
	}
}
```
:::
::: tab C#
```cs title=Program.cs lines {6-7}
using static System.Globalization.CultureInfo;

var totals = File.ReadLines("orders.csv")
    .Skip(1)
    .Select(line => line.Split(','))
    .GroupBy(c => c[0])
    .Select(g => (Name: g.Key, Total: g.Sum(c => decimal.Parse(c[1], InvariantCulture))))
    .OrderByDescending(t => t.Total);

foreach (var (name, total) in totals)
    Console.WriteLine($"{name,-15} {total,8:F2}");
```
:::
::: tab SQL
```sql title=totals.sql lines {1,3}
SELECT customer, SUM(amount) AS total
FROM orders
GROUP BY customer
ORDER BY total DESC;
```
:::
::: tab Shell
```sh title=totals.sh lines {2-3}
tail -n +2 orders.csv |
  awk -F, '{ t[$1] += $2 }
    END { for (c in t) printf "%8.2f  %s\n", t[c], c }' |
  sort -rn
```
:::
::: tab AutoHotkey
```ahk title=totals.ahk lines {7-8}
#Requires AutoHotkey v2.0

totals := Map()
for line in StrSplit(FileRead("orders.csv"), "`n", "`r") {
    if A_Index = 1 || line = ""
        continue
    cols := StrSplit(line, ",")
    totals[cols[1]] := totals.Get(cols[1], 0) + Round(cols[2] * 100)
}
report := ""
for customer, cents in totals
    report .= Format("{:.2f}`t{}`n", cents / 100, customer)
MsgBox Sort(report, "N R"), "Totals"
```
:::

## What goes in and what comes out

Every version reads the same six orders, in euros:

```text title=orders.csv
customer,amount
Okafor Bakery,184.50
Lumen Studio,92.00
Okafor Bakery,61.25
Hart & Vale,240.00
Lumen Studio,38.40
Hart & Vale,17.60
```

and prints the same three lines:

```text title=output
Hart & Vale       257.60
Okafor Bakery     245.75
Lumen Studio      130.40
```

::: tip Add up cents, not euros
A computer's ordinary numbers cannot hold 0.10 exactly, so a long column of amounts can end up a cent out. Most versions here add whole cents, or Python's and C#'s decimal numbers, for that reason.
:::

## Sort by name instead

One line changes in the Python version:

```diff title=totals.py
-for customer, total in sorted(totals.items(), key=lambda t: -t[1]):
+for customer, total in sorted(totals.items()):
     print(f"{customer:<15} {total:>8.2f}")
```

## Run it

::: tab macOS and Linux
```sh
python3 totals.py
npx tsx totals.ts
cargo run --quiet
go run main.go
sqlite3 shop.db < totals.sql
sh totals.sh
```
:::
::: tab Windows
```powershell
py totals.py
npx tsx totals.ts
cargo run --quiet
go run main.go
dotnet run
& "$env:ProgramFiles\AutoHotkey\v2\AutoHotkey64.exe" totals.ahk
```
:::

---

## How it's made

- **A code block** is three backticks, a language name, the code and three backticks. The language picks the colours, which come from your theme, so they follow light and dark. A block marked `text` stays plain.
- **Words after the language** add the rest: `title=totals.py` names the file, `lines` numbers the lines, and `{7-8}` marks lines 7 and 8. `{1,3}` marks two lines apart.
- **Tabs** are `::: tab Name` blocks one after another. Next to each other they become one set, so the eight versions above share one box, and the two under Run it make a second set.
- **The tip** is a `::: tip Title` block, drawn by the callout plugin. Hover a code block for its Copy button.

## Try it yourself

1. On the Python fence, change `{7-8}` to `{11}`. Only the print line stays marked.
2. Remove `lines` from the same fence. The line numbers go, and the marked line stays marked.
3. Add a ninth tab, `::: tab Ruby`, with a fenced `ruby` block and a closing `:::`, right after the AutoHotkey tab. It joins the same set.
4. Change `::: tip Add up cents, not euros` to `::: warning Add up cents, not euros`. The box takes the warning colour.

Next: *Design document* puts diagrams next to its decisions; *Live HTML sketches* runs HTML you write instead of showing it.