# btw cheat sheet

Generated from docs/BTW.md by `btwd cheatsheet`. btw writes a whole track as text: pattern lines become Petri nets on decks A and B, every other line is a control call, and the same canonical text always has the same CID. The grammar and rules below are authoritative: run `check` and fix every `line:col` error before playing.

## The rules in one screen

- A program is **lines**. A line is blank, a `# comment`, or one statement. A line that starts with
  `|` continues the statement above it.
- Words are lower case. Deck names are `A` and `B`. Numbers are plain: `5`, `0.7`, `2k` (= 2000),
  `50%` (= 0.5).
- A statement is `[when:] [target:] body`. Each head ends in a colon, and they read left to right:
  *when* (`every 16 bars`), *whose* (`deck A`, `master`), then *what*.
- Time is **bars** (four beats). Nothing here is in seconds. A pattern is one **cycle** (one bar)
  long, and its terms share the cycle equally.
- Text in, same net out: the same program text always gives the same net CIDs and the same program CID.

## Grammar (EBNF)

`{ x }` zero or more, `[ x ]` optional, `( a | b )` choice, `"x"` a literal word or mark.
Whitespace separates tokens and is otherwise free; a line end ends a statement (except before `|`).

```ebnf
program = { line } ;
line = [ statement ] [ comment ] NEWLINE ;
comment = "#" { any character but NEWLINE } ;  (* "#" inside a word is a sharp: f#, a#4 *)
statement = setting | headed | let | def | repeat | section | arrange | end | loop | evolve ;
setting = "tempo" number
    | "swing" number
    | "key" key ;
headed = [ when ] [ "for" int "bars" ] ":" [ target ":" ] body ;
when = "every" int "bars" [ "from" int ]
    | "on" "phrase" | "on" "next" "bar" | "on" "next" "phrase" [ 8 | 16 | 32 ]
    | "at" "bar" int | "after" NAME | "before" NAME int "bars" ;
target = "deck" deck | "master" ;
deck = "A" | "B" ;
body = parts | action | do | defcall ;
parts = part { "|" part } ;  (* only after "deck X:" and with no `when` *)
part = role pattern { param } ;
role = "kick" | "snare" | "hihat" | "clap"  (* drum parts: a hit plays the drum's note *)
    | "bass" | "melody" | "harmony" | "arp" ;  (* tonal parts: a hit plays the key's root *)
param = NAME "=" ( number [ ".." number ] | word ) ;  (* vel oct len seed inst kit sound route *)
pattern = { term } ;  (* at least one *)
term = atom [ "!" ] [ "^" ] [ "*" int ] ;  (* accent, slide *)
atom = "x"  (* a hit *)
    | "~"  (* a rest *)
    | note  (* c3  f#2  bb4 *)
    | int  (* a scale degree of the key: 1 3 5 *)
    | "[" pattern { "," pattern } "]"  (* a group: squeezed into one slot; commas stack *)
    | "<" pattern ">"  (* alternation: one term per cycle *)
    | call ;
call = NAME "(" [ arg { "," arg } ] ")" ;  (* a generator, below *)
arg = number | key | chord | NAME | NAME "=" ( number | word ) | "[" pattern "]" | call ;
note = ( "a".."g" ) [ "#" | "b" ] [ int ] ;  (* octave 4 = middle C; omitted: the part's own *)
key = tonic [ "m" ] | tonic ":" mode ;  (* am  c  f#m  d:dorian *)
tonic = ( "a".."g" ) [ "#" | "b" ] ;
mode = "major" | "minor" | "dorian" | "mixolydian" | "phrygian"
    | "harmonic" | "pent" | "minpent" | "blues" ;
chord = tonic quality ;  (* am7  c  cmaj7  g7  dsus4  f#m7b5 *)
quality = "" | "m" | "7" | "m7" | "maj7" | "dim" | "aug" | "sus2" | "sus4" | "5" | "6" | "m6" | "9" | "m9" | "m7b5" ;
action = "filter" ( "lp" | "hp" ) change  (* hertz: 20 .. 20k *)
    | "filter" ( "off" | "open" )
    | ( "delay" | "reverb" | "crush" ) change  (* 0 .. 1: how much *)
    | ( "level" | "low" | "mid" | "high" ) change  (* deck X: / master: level *)
    | ( "resonance" ) change ;  (* with the actions above *)
change = value [ "->" value ] [ span ] ;  (* 2k -> 8k over 8 bars *)
span = "over" int "bars" ;
value = number [ "->" number ] | word | STRING | "[" [ value { "," value } ] "]" ;
evolve = "evolve" "every" int "bars" "{" { rule } bound "}" ;
rule = ( role | "deck" deck ) ":" op { "|" op } [ "when" "gen" [ "%" int ] cmp int ] ;
op = ( "rotate" | "transpose" | "octave" | "invert" | "reverse" | "thin" ) { number | "<" number { number } ">" } [ "seed=" int ] ;
bound = "stop" "when" "gen" ( "==" | ">=" | ">" ) int | "for" int "gens" ;
end = "end" [ "at" "bar" int | "after" NAME ] ;  (* a song ends after its last section by default *)
loop = "loop" ;  (* a song starts again at its end *)
let = "let" NAME "=" ( token | pattern ) ;  (* one token: a value; more: a pattern *)
def = "def" NAME "(" [ NAME { "," NAME } ] ")" "{" { line } "}" ;  (* $NAME inside *)
repeat = "repeat" int [ "every" int "bars" ] "{" { line } "}" ;  (* the count is written out *)
section = "section" NAME int "bars" "{" { statement } "}" ;
arrange = "arrange" NAME { NAME } ;
do = [ "do" ] NOUN [ VERB ] { STRING } { NAME "=" value } [ "over" int "bars" ] ;
defcall = NAME "(" [ tokens { "," tokens } ] ")" ;  (* a def's call *)
```

`NAME` is a lower-case word (letters, digits, `_`, and `-` between letters). `int` is a whole number;
`number` also takes a fraction and the `k` / `%` marks. `NEWLINE` also ends the program at the end of
the text.

## Patterns: mini-notation

```text
kick x ~ x ~  4 terms: quarter notes, hits on 1 and 3
kick x x x x x x x x  8 terms: eighths
snare ~ x ~ x  hits on 2 and 4
hihat x*8  eight hits: x*8 is x in each eighth of the bar
hihat [x x] x [x x] x  groups: two hits squeezed into one slot
bass c2 ~ [c2 eb2] g2  notes
bass 1 ~ 3 5  scale degrees of the key
melody <c4 e4 g4>  alternation: c4 on the first bar, e4 on the second, g4 on the third, then round
kick e(5,8)  euclid: five hits over eight steps
kick e(3,8,2)  the same, rotated by two
harmony [c3,e3,g3]  a comma inside [] stacks: three notes at once
```

- `*n` plays its term `n` times in its slot. `<a b>*2` is `a b` inside one bar (the alternation
  advances twice).
- A pattern with an alternation is as many bars long as the alternation needs (the least common
  multiple of the alternations in the deck's parts, at most 64 bars). The net is that long and loops.
- The grid is sixteenths. A term that does not fall on a sixteenth (three in a bar, five in a bar)
  snaps to the nearest one, and `check` says so as a warning: `x x x` does not divide 16 steps; its
  hits snap to steps 0, 5, 11.
- A hit in a drum part plays that drum's note. A hit in a tonal part plays the key's root in the part's
  octave. A note plays that note. A degree plays that step of the key's scale (`1` the root, `8` the root
  an octave up).
- Default octaves: bass 2, harmony 3, melody 4, arp 4. `oct=N` sets it.

### Generators

| call | does |
|---|---|
| `e(k, n)` / `e(k, n, rot)` / `euclid(...)` | `k` hits over `n` steps, rotated by `rot`. As a term it takes one slot, so `kick e(5,8)` is a bar of eight steps and `kick x e(3,8)` puts the eight steps in the second half. |
| `markov(key, density)` / `markov(density)` / `markov(key, density, seed)` | a Markov melody of one bar in the key's scale. The key is the program's `key` when left out. `density` 0..1. Same seed, same notes: the seed is, when left out, taken from the text of the part, so a program is the same net every time. |
| `arp(chord, mode, n)` | the chord's notes one at a time over `n` steps (default 8) in `up`, `down` or `updown`. |
| `chord(chord)` / `chord(chord, octave)` | the chord's notes together. |

### Parameters

| param | value | does |
|---|---|---|
| `vel=90` / `vel=70..100` | 1..127 | velocity. A range gives each hit a velocity in it, picked by a hash of its place: the same text gives the same velocities, not a random walk. |
| `oct=2` | -1..8 | the part's octave. |
| `len=3` | 1..16 | note length in steps (drums 1, tonal 2). |
| `inst=sub-bass` | a name | the instrument. |
| `seed=7` | a whole number | the seed of the part's generators. |

A **range** `a..b` is *any value from a to b*, and it is only ever for a parameter of a part. A **ramp**
`a -> b` is *moving from a to b*, and it is only for a control change, with `over N bars`.

### Settings

`tempo 126` (BPM, 40..300), `swing 0.1` (0..1), `key am`. A setting applies to the whole program. `key`
is the default for notes with no octave, scale degrees, `markov`, and the key tag the share carries.
No `key`: C major. No `tempo`: the decks keep theirs.

## Control

```text
master: filter lp 2k
deck A: filter hp 400
master: filter off
master: delay 0.4
master: reverb 0.3 / crush 0.5
master: level 0.8
deck A: level 0.7 / low 0 / mid / high
```

### Time words

Any line can have a time word, then the target, then what it does: `at bar 16 for 4 bars: master: filter lp 800`.

| word | fires |
|---|---|
| (none) | once, on the first bar line after the statement is added or changed (in a `section`: on its first bar) |
| `every 16 bars:` | on bars 16, 32, 48 ... (never on bar 0) |
| `every 4 bars from 8:` | on bars 8, 12, 16 ... |
| `on phrase:` | on bars 8, 16, 24 ...: every phrase |
| `on next bar:` | once, now (the same as no word) |
| `on next phrase [8\|16\|32]:` | once, on the first bar that is a multiple of 8 (or 16, 32) |
| `at bar 32:` | once, on bar 32 (in a `section`: bar 0 is its first bar, so `at bar 4` is the fifth) |
| `after drop:` | once, on the bar the section `drop` ends on |
| `before drop 4 bars:` | once, four bars ahead of the section: the roll that leads into a drop |
| `for 4 bars` | after any of the above: the effect is **put back** after four bars (`for 4 bars:` alone is now) |

## The whole surface: `do`

```text
do <noun> [<verb>] [<positional text>] key=value ... [over N bars]
```

```text
every 16 bars: freeze phrase bars=2
at bar 8 for 4 bars: trick on deck=A kind=stutter
vocal create "robots on the road" key=am bars=4
do vocoder set mix=0 -> 1 over 8 bars
do td3 write confirm=true
```

## Functions and structure

Everything here is **total**: there is no recursion and no loop without a written-out count, so `check`
always proves a program ends, and the same text always gives the same CIDs.

```text
let kicks = x ~ ~ ~ ~ ~ ~ ~ ~ ~ x ~ ~ ~ ~ ~  # a pattern: used where a pattern goes, as a group
let late = 8  # a value: put in place of every later use
let root = c2

def groove(deck, bars) {  # a macro, expanded at each call
  deck $deck: kick kicks | bass root ~ root ~
  repeat $bars every 1 bars {  # a literal count; $i is the copy's index
    master: filter lp 300 -> 2800 over 1 bars
  }
}

section drop 16 bars {  # lines in it count from its first bar
  master: filter off
  groove(A, 16)
}
arrange intro build drop breakdown drop2 outro
```

- **`let name = ...`** at the top. One token (`8`, `c2`, `am`) is a value put in place of every later use of
  the name (so `at bar late:` and `bass root` work, and the canonical text shows the value). More tokens are a
  pattern, used as `bass kicks`, in `<a b>` alternations, in `[a, b]` stacks and as the pattern a transform
  takes. A name cannot be a word of the language, a note, a chord or a key (`let kick` and `let a` are errors).
- **`def name(a, b) { ... }`** is a macro: its body is lines, and `$a` is where an argument goes. A call
  `name(x, y)` is a line, with `at bar N:` / `after X:` / `before X N bars:` or none. The body is read when it
  is called, so an error in it says where in the def and which call. **A def that calls itself, directly or
  through another def, is an error** (`ping -> pong -> ping`) found before anything runs.
- **`repeat N { ... }`** with `N` written out (1 to 64). `repeat 8 every 2 bars { ... }` shifts copy `i` by
  `i * 2` bars; `$i` and `$n` are the index and the count. Nested, a program may expand to 4096 lines.
- **`section name N bars { ... }`** and **`arrange a b c`**: the song is the sections in that order (a section
  may be named twice; without `arrange`, in the order written). Lines outside every section apply to the whole
  song, a section's own part of the same role wins, and a deck a section does not use is stopped there. The
  nets of the next section are loaded a bar ahead and land on its bar line. After the last section the last
  nets play on. `section` and `arrange` belong at the top, not inside another block.

### Ending

| line | does |
|---|---|
| `end` | the same as the default: after the song's last section |
| `end after outro` | where the section `outro` ends (the song stops there, later sections never play) |
| `end at bar 64` | on bar 64 of the song (of the program, with no sections) |
| `loop` | the old behaviour for a song: at its end it starts again from the first section, its `at` lines firing again each lap |

### Evolving

```text
section drop 32 bars {
  deck B: melody [a4 c5 e5 g5] | bass [a2 ~ e2 ~]
  deck A: kick x ~ x ~ | hihat x*8
  evolve every 8 bars {
    melody: rotate 1 | transpose <0 5 7 0>
    hihat: thin 0.1 seed=3
    bass: invert when gen % 2 == 1
    stop when gen == 3
  }
}
```

| transform | does |
|---|---|
| `rotate n` | every hit `n` steps (sixteenths) along its bar, wrapping |
| `reverse` | the steps of a bar backwards |
| `transpose n` / `octave n` | pitches up `n` semitones / octaves (tonal parts; a drum's note is the drum) |
| `invert` | pitches turned over about the part's first note (tonal parts) |
| `thin p [seed=s]` | drops the share `p` of the hits, picked by a hash of (seed, generation, bar, step, note): the same seed, the same hits |

An argument `<0 5 7 0>` takes one value per generation, round (generation 1 the first). A guard is `gen == 3`,
`gen % 4 == 3`, `gen >= 8` (also `!=`, `<`, `<=`, `>`): the rule runs in the generations it is true for.

### Pattern transforms

Terms like generators; a pattern is given as `[...]`, a `let` name, or another transform:

| call | does |
|---|---|
| `transpose(p, n)` / `octave(p, n)` | `n` semitones / octaves up (a hit in a tonal part is its root first) |
| `reverse(p)` / `rotate(p, n)` | the steps backwards / moved `n` steps along |
| `every(n, p)` / `every(n, p, q)` | `p` on every `n`th bar (the 4th, 8th ...), `q` (or a rest) on the others |
| `degrade(p, a)` / `degrade(p, a, seed)` | drops the share `a` of the hits: seeded, so the same text is the same hits |
| `slow(p, n)` / `fast(p, n)` | `p` stretched over `n` bars / played `n` times a bar |
| `humanize(p, seed)` / `humanize(p, seed, amount)` | velocities wander by up to `amount` (default 10), seeded |

An accent is `!` and a slide `^` right after a step: `c2! e2^ g2`. An accent is a harder hit (velocity +27); a
slide holds the note into the next step.

## Sounds

| param | takes | does |
|---|---|---|
| `inst=wobble-lead` | a voice | the part's instrument. An unknown name is an **error with the nearest names**; a family word (`inst=reese`) is accepted with a **warning** that it plays the generic saw bass, and which voices have a sound of their own |
| `kit=drums-808` | a kit | a drum part's kit (set once the net has landed) |
| `sound=synth:wobble-lead` | `own`, `synth`, `synth:NAME`, `inst:NAME` | the role's sound option on the deck, set once the net has landed |

## On btw.bitwrap.io

- Programs are public and CC0: `sample`, `loop`, `use restricted` and `import` are not available. The desktop booth's lines (`swap pairs`, `move`, `load`, `queue`, `crossfader`, `play`, `stop`, `sync`, `mute`) check but belong to the app: leave them out.
- `inst=NAME` is a voice from `/api/instruments` or a family word (a warning says it plays the family's generic voice); `kit=NAME` is a drum kit. An unknown name is an error with the nearest names.
- Formatting never changes the CID: the canonical text is the parse printed again (comments dropped, numbers shortest, notes lower case with sharps).
