barmark 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -9,6 +9,50 @@ Releases follow the process in [RELEASING.md](RELEASING.md).
9
9
 
10
10
  ## [Unreleased]
11
11
 
12
+ ## [0.12.0] - 2026-11-03
13
+
14
+ Rehearsal marks and words on a bar, issue #70 (grammar 2.5 and 2.6);
15
+ omissions, voicings, accents, hits and push marks (grammar 2.7, 2.8, 3
16
+ and 4.2).
17
+
18
+ ### Added
19
+
20
+ - **Rehearsal marks:** `@` and a label of letters and digits, alone in a
21
+ cell (`| @B | D | A |`), marks the bar after it. A mark is not a bar
22
+ and takes no time; a repeat or replay plays it with its bar. Cells
23
+ gain `kind: "rehearsal"`, and played bars `rehearsal`, the label.
24
+ - **Words on a bar:** quoted words in a cell (`| "solo" D |`,
25
+ `| D "rit." G |`) sit before the slot they precede, or at the bar's
26
+ end after the last. Curly quotes are accepted. They carry no musical
27
+ meaning. Cells and played bars gain `words` (`{ text, at }`), present
28
+ only when written.
29
+ - **Omissions:** `no3` and `no5` in a chord's parentheses leave out its
30
+ third or fifth (`C7(no3)`, `C7(b9,no5)`). `(omit3)` and `(omit 3)`
31
+ are accepted and print as `(no3)`; `C(no3)` prints as `C5`. Harte
32
+ labels mark them with `*` (`C:7(*3)`).
33
+ - **Voicings:** a chord name followed by a note set gives the chord and
34
+ its exact notes (`Cmaj7{E3 G3 B3 C4}`). Every note must be in the
35
+ chord. Chord slots gain `voicing`, and it transposes with the chord.
36
+ - **Accents and hits:** `>D` accents a chord or note set and `^D` makes
37
+ it a hit, short and accented. Chord slots gain `articulation`
38
+ (`"accent"` or `"hit"`).
39
+ - **Push marks:** `<D` arrives an eighth early and `<<D` a sixteenth,
40
+ taking the time from the slot played just before it in play order,
41
+ so a pushed downbeat works inside repeats, replays and jumps. Chord,
42
+ `N.C.` and `--` slots gain `push` (`"eighth"` or `"sixteenth"`).
43
+ - **Errors with line numbers** for an omission the chord can't make, a
44
+ voicing note not in its chord, an accent on anything but a chord or
45
+ note set, a push with nothing before it or longer than the slot it
46
+ borrows from, a push on `/`, `%`, `?` or inside a group, and `^<D`
47
+ (with the fix `<^D`); and for a mark that shares its cell (with
48
+ the fix), a bad label, a mark with no bar after it, two marks on one
49
+ bar, an unclosed quote, empty quotes and words with no bar.
50
+
51
+ ### Fixed
52
+
53
+ - **A bar line dropped for an error no longer counts its directions as
54
+ bars** in the written numbers of the bars after it.
55
+
12
56
  ## [0.11.0] - 2026-11-03
13
57
 
14
58
  Endings and directions, issue #70 (grammar 5.1 and 5.2).
@@ -260,7 +304,8 @@ The first working release: the reference parser and printer for the
260
304
 
261
305
  - **A placeholder package that holds the `barmark` name** while the spec and parser are written.
262
306
 
263
- [Unreleased]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.11.0...HEAD
307
+ [Unreleased]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.12.0...HEAD
308
+ [0.12.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.11.0...barmark-v0.12.0
264
309
  [0.11.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.10.0...barmark-v0.11.0
265
310
  [0.10.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.9.0...barmark-v0.10.0
266
311
  [0.9.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.8.0...barmark-v0.9.0
@@ -1,14 +1,16 @@
1
- import type { Cell, ChartDiagnostic, Line, Meter, Repeat, Slot } from "./types.js";
1
+ import type { Cell, ChartDiagnostic, Line, Meter, Repeat, Slot, Words } from "./types.js";
2
2
  type BarsLine = Extract<Line, {
3
3
  kind: "bars";
4
4
  }>;
5
- /** Whether a cell is a bar: `...` and a direction mark a place between bars. */
5
+ /** Whether a cell is a bar: `...`, a direction and a rehearsal mark mark a place between bars. */
6
6
  export declare const isBar: (c: Cell) => c is {
7
7
  kind: "slots";
8
8
  meter: Meter | null;
9
9
  slots: Slot[];
10
+ words?: Words[];
10
11
  } | {
11
12
  kind: "simile";
13
+ words?: Words[];
12
14
  };
13
15
  /** The `x N` or `x ...` count after a bar line or heading, checked against the spec's limits. */
14
16
  export declare function readRepeat(count: string, line: number, diagnostics: ChartDiagnostic[]): Repeat;
@@ -1,10 +1,13 @@
1
+ import { noteSemitone } from "../chords/intervals.js";
1
2
  import { parseNoteSet } from "../chords/noteSet.js";
2
3
  import { parseChord } from "../chords/parse.js";
3
4
  import { isDirectionWord, readDirection } from "./direction.js";
4
5
  import { parseMeter } from "./directives.js";
5
6
  const FERMATA = new Set(["...", "…"]);
6
- /** Whether a cell is a bar: `...` and a direction mark a place between bars. */
7
- export const isBar = (c) => c.kind !== "fermata" && c.kind !== "direction";
7
+ /** Whether a cell is a bar: `...`, a direction and a rehearsal mark mark a place between bars. */
8
+ export const isBar = (c) => c.kind === "slots" || c.kind === "simile";
9
+ const QUOTES = new Set(['"', "“", "”", "„"]);
10
+ const LABEL = /^@[A-Za-z0-9]+$/;
8
11
  const SILENCE = new Set(["--", "–", "—"]);
9
12
  /** The `x N` or `x ...` count after a bar line or heading, checked against the spec's limits. */
10
13
  export function readRepeat(count, line, diagnostics) {
@@ -162,7 +165,166 @@ const barsWritten = (body) => body
162
165
  .split("|")
163
166
  .slice(1)
164
167
  .map((p) => p.trim())
165
- .filter((p) => p !== "" && !FERMATA.has(p)).length;
168
+ .filter((p) => p !== "" && !FERMATA.has(p) && !LABEL.test(p) && !isDirectionCell(p)).length;
169
+ const isDirectionCell = (p) => {
170
+ const d = readDirection(p);
171
+ return !!d && "direction" in d;
172
+ };
173
+ /**
174
+ * Quoted words out of a cell (grammar 2.6): the cell with each one blanked,
175
+ * and where each goes, before the slot it precedes.
176
+ */
177
+ function readWords(cell) {
178
+ const words = [];
179
+ let bare = "";
180
+ let open = null;
181
+ for (const [i, ch] of [...cell].entries()) {
182
+ if (!QUOTES.has(ch)) {
183
+ if (open === null)
184
+ bare += ch;
185
+ continue;
186
+ }
187
+ if (open === null) {
188
+ open = i;
189
+ continue;
190
+ }
191
+ const text = [...cell]
192
+ .slice(open + 1, i)
193
+ .join("")
194
+ .trim();
195
+ if (!text)
196
+ return { problem: "empty words between quotes", token: '""' };
197
+ words.push({ text, at: tokens(bare).length });
198
+ bare += " ";
199
+ open = null;
200
+ }
201
+ if (open !== null)
202
+ return { problem: "words need a closing quote", token: [...cell].slice(open).join("") };
203
+ return { bare, words };
204
+ }
205
+ /** A leading `[n/d]` and the rest of the cell; `bad` is a bracket that is no time signature. */
206
+ function readMeter(cell) {
207
+ const bracket = /^\[([^\]]*)\]/.exec(cell);
208
+ if (!bracket)
209
+ return { meter: null, after: cell, bad: null };
210
+ const meter = parseMeter(bracket[1] ?? "");
211
+ return { meter, after: cell.slice(bracket[0].length).trim(), bad: meter ? null : bracket[0] };
212
+ }
213
+ const emptyCell = (words) => words.length ? "words go on a bar; this cell has no slot" : "a cell needs at least one slot";
214
+ /** `%` or `...` alone in a cell, or what is wrong with it; null when the cell is neither. */
215
+ function symbolCell(bare, meter, words) {
216
+ const only = tokens(bare);
217
+ const t = only[0] ?? "";
218
+ if (only.length !== 1 || (t !== "%" && !FERMATA.has(t)))
219
+ return null;
220
+ if (meter)
221
+ return { problem: "a one-bar meter cannot go on % or ...", token: t };
222
+ if (t !== "%")
223
+ return words.length
224
+ ? { problem: "words go on a bar, not on ...", token: t }
225
+ : { cell: { kind: "fermata" } };
226
+ // Words on `%` go on the whole bar.
227
+ const onBar = words.map((w) => ({ ...w, at: 0 }));
228
+ return { cell: words.length ? { kind: "simile", words: onBar } : { kind: "simile" } };
229
+ }
230
+ /** A direction alone in a cell, or what is wrong with it; null when the cell isn't one. */
231
+ function directionWithWords(bare, meter, words) {
232
+ const token = bare.trim();
233
+ const d = directionCell(token, meter);
234
+ if (!d)
235
+ return null;
236
+ if (!("cell" in d))
237
+ return { problem: d.problem, token, ...(d.suggestion ? { suggestion: d.suggestion } : {}) };
238
+ return words.length ? { problem: "words go on a bar, not on a direction", token } : d;
239
+ }
240
+ const ARTICULATION = { ">": "accent", "^": "hit" };
241
+ const PUSH = { 1: "eighth", 2: "sixteenth" };
242
+ /** A slot's leading marks (grammar 2.7, 2.8): a push, then an articulation, then the slot itself. */
243
+ function readMarks(token) {
244
+ const pushes = /^<*/.exec(token)?.[0].length ?? 0;
245
+ const push = PUSH[pushes];
246
+ if (pushes && !push)
247
+ return { problem: "a push is < (an eighth) or << (a sixteenth)", token };
248
+ const marked = readArticulation(token.slice(pushes), token);
249
+ return "problem" in marked ? marked : { ...(push ? { push } : {}), ...marked };
250
+ }
251
+ /** A leading `>` or `^`, and the slot after it; a push after it is written in the wrong order. */
252
+ function readArticulation(text, token) {
253
+ const articulation = ARTICULATION[text[0] ?? ""];
254
+ if (!articulation)
255
+ return { rest: text };
256
+ const rest = text.slice(1);
257
+ if (!rest.startsWith("<"))
258
+ return { articulation, rest };
259
+ const suggestion = rest.replace(/^(<+)/, `$1${text[0]}`);
260
+ return { problem: "a push and an accent: write the push first", token, suggestion };
261
+ }
262
+ const UNPUSHABLE = new Set(["/", "?", "%", "...", "…"]);
263
+ /** Why these marks can't go on this slot; null when they can. */
264
+ function marksProblem(marks, inGroup, token) {
265
+ if (marks.push && inGroup)
266
+ return { problem: "a push goes on a whole slot, not inside a group", token };
267
+ if (marks.push && UNPUSHABLE.has(marks.rest))
268
+ return { problem: "a push goes on a chord, a note set, N.C. or --", token };
269
+ const plain = UNPUSHABLE.has(marks.rest) || SILENCE.has(marks.rest) || /^n\.?c\.?$/i.test(marks.rest);
270
+ if (marks.articulation && plain)
271
+ return { problem: "an accent or a hit goes on a chord or a note set", token };
272
+ return null;
273
+ }
274
+ /** Whether a voicing's note is one of the chord's, by pitch class. */
275
+ const inChord = (note, chord) => {
276
+ const pc = (n) => (noteSemitone(n.replace(/\d|!/g, "")) + 12) % 12;
277
+ return chord.pitches.some((p) => pc(p) === pc(note));
278
+ };
279
+ /** `Cmaj7{E3 G3 B3}`: the chord, and the notes it is voiced with, each one of its own (grammar 4.2). */
280
+ function parseVoiced(token, brace) {
281
+ const chord = parseChord(token.slice(0, brace));
282
+ if (!chord.ok)
283
+ return {
284
+ problem: chord.error.message,
285
+ token,
286
+ ...(chord.error.suggestion ? { suggestion: chord.error.suggestion } : {}),
287
+ };
288
+ const voicing = parseNoteSet(token.slice(brace));
289
+ if (!voicing.ok)
290
+ return { problem: voicing.error.message, token: voicing.error.token };
291
+ const stray = voicing.value.pitches.find((n) => !inChord(n, chord.value));
292
+ if (stray)
293
+ return {
294
+ problem: `${stray.replace(/\d/g, "")} is not in ${chord.value.canonical}`,
295
+ token: stray,
296
+ };
297
+ return { chord: chord.value, voicing: voicing.value, warnings: [chord, voicing] };
298
+ }
299
+ /** A cell that is one thing alone (a mark, a direction, `%` or `...`), or what is wrong with it. */
300
+ const standalone = (bare, meter, words) => rehearsalCell(bare, meter, words) ??
301
+ directionWithWords(bare, meter, words) ??
302
+ symbolCell(bare, meter, words);
303
+ /** A `@B` cell, or what is wrong with one; null when the cell has no mark. */
304
+ function rehearsalCell(bare, meter, words) {
305
+ const list = tokens(bare);
306
+ const at = list.findIndex((t) => t.startsWith("@"));
307
+ const mark = list[at];
308
+ if (mark === undefined)
309
+ return null;
310
+ if (!LABEL.test(mark))
311
+ return {
312
+ problem: "a rehearsal mark is @ and a label of letters and digits, like @B or @17",
313
+ token: mark,
314
+ };
315
+ if (words.length)
316
+ return { problem: "words go on a bar, not on a rehearsal mark", token: mark };
317
+ if (meter)
318
+ return { problem: "a one-bar meter cannot go on a rehearsal mark", token: mark };
319
+ if (list.length === 1)
320
+ return { cell: { kind: "rehearsal", label: mark.slice(1) } };
321
+ const others = list.filter((_, i) => i !== at).join(" ");
322
+ return {
323
+ problem: "a rehearsal mark is a cell of its own",
324
+ token: mark,
325
+ suggestion: `| ${mark} | ${others} |`,
326
+ };
327
+ }
166
328
  /**
167
329
  * One bar line: cells between pipes, each cell's slots, the `|:` and `:|`
168
330
  * marks and an `x N` tail. Any error drops the whole line (`bars` is null);
@@ -221,6 +383,7 @@ export function parseBarLine(text, line) {
221
383
  parts.pop();
222
384
  else
223
385
  warn("missing trailing |", parts.at(-1)?.trim() ?? "");
386
+ const report = (p) => error(p.problem, p.token, p.suggestion);
224
387
  const simple = (token) => {
225
388
  if (token === "/")
226
389
  return { kind: "hold" };
@@ -240,81 +403,85 @@ export function parseBarLine(text, line) {
240
403
  const alone = mustStandAlone(token);
241
404
  if (alone)
242
405
  return error(alone, token);
243
- const r = token.startsWith("{") ? parseNoteSet(token) : parseChord(token);
406
+ return chordSlot(token);
407
+ };
408
+ /** A chord, a note set, or a chord with its voicing. */
409
+ const chordSlot = (token) => {
410
+ const brace = token.indexOf("{");
411
+ if (brace > 0) {
412
+ const v = parseVoiced(token, brace);
413
+ if ("problem" in v)
414
+ return report(v);
415
+ for (const r of v.warnings)
416
+ for (const w of r.ok ? r.warnings : [])
417
+ warn(w.message, w.token);
418
+ return { kind: "chord", chord: v.chord, voicing: v.voicing };
419
+ }
420
+ const r = brace === 0 ? parseNoteSet(token) : parseChord(token);
244
421
  if (!r.ok)
245
422
  return error(r.error.message, token, r.error.suggestion);
246
423
  for (const w of r.warnings)
247
424
  warn(w.message, w.token);
248
425
  return { kind: "chord", chord: r.value };
249
426
  };
427
+ /** A slot with its push and articulation, if written. */
428
+ const markedSlot = (token, inGroup) => {
429
+ const marks = readMarks(token);
430
+ if ("problem" in marks)
431
+ return report(marks);
432
+ const problem = marksProblem(marks, inGroup, token);
433
+ if (problem)
434
+ return report(problem);
435
+ const base = simple(marks.rest);
436
+ const { push, articulation } = marks;
437
+ return (base &&
438
+ {
439
+ ...base,
440
+ ...(push ? { push } : {}),
441
+ ...(articulation ? { articulation } : {}),
442
+ });
443
+ };
444
+ /** One slot token: a simple slot, or a `_` group of them. */
445
+ const slotOf = (token) => {
446
+ const members = groupMembers(token);
447
+ if (members.length === 1)
448
+ return markedSlot(token, false);
449
+ const out = [];
450
+ for (const m of members) {
451
+ const s = m ? markedSlot(m, true) : error("an empty member in a group", token);
452
+ if (s)
453
+ out.push(s);
454
+ }
455
+ return { kind: "group", members: out };
456
+ };
457
+ const readCell = (raw) => {
458
+ const rest = raw.trim();
459
+ if (!rest)
460
+ return error("an empty cell; use / to hold or % to repeat", "| |");
461
+ const { meter, after, bad } = readMeter(rest);
462
+ if (bad)
463
+ error("not a time signature", bad);
464
+ const read = readWords(after);
465
+ if ("problem" in read)
466
+ return report(read);
467
+ const { bare, words } = read;
468
+ if (bare.includes("["))
469
+ return error("a [n/d] meter must start its cell", rest);
470
+ const alone = standalone(bare, meter, words);
471
+ if (alone)
472
+ return "cell" in alone ? alone.cell : report(alone);
473
+ return slotsCell(bare, meter, words, raw.trim());
474
+ };
475
+ const slotsCell = (bare, meter, words, raw) => {
476
+ const slots = tokens(bare).map(slotOf);
477
+ if (!slots.length)
478
+ return error(emptyCell(words), raw);
479
+ const kept = slots.filter((x) => x !== null);
480
+ return { kind: "slots", meter, slots: kept, ...(words.length ? { words } : {}) };
481
+ };
250
482
  if (parts.length === 0)
251
483
  error("a bar line needs at least one cell", text.trim());
252
- const cells = [];
253
- for (const raw of parts) {
254
- let rest = raw.trim();
255
- if (!rest) {
256
- error("an empty cell; use / to hold or % to repeat", "| |");
257
- continue;
258
- }
259
- let meter = null;
260
- const bracket = /^\[([^\]]*)\]/.exec(rest);
261
- if (bracket) {
262
- meter = parseMeter(bracket[1] ?? "");
263
- if (!meter)
264
- error("not a time signature", bracket[0]);
265
- rest = rest.slice(bracket[0].length).trim();
266
- }
267
- if (rest.includes("[")) {
268
- error("a [n/d] meter must start its cell", rest);
269
- continue;
270
- }
271
- const direction = directionCell(rest, meter);
272
- if (direction && "cell" in direction)
273
- cells.push(direction.cell);
274
- else if (direction)
275
- error(direction.problem, rest, direction.suggestion);
276
- if (direction)
277
- continue;
278
- const list = tokens(rest);
279
- if (list.length === 0) {
280
- error("a cell needs at least one slot", raw.trim());
281
- continue;
282
- }
283
- if (list.length === 1 && meter && (list[0] === "%" || FERMATA.has(list[0] ?? ""))) {
284
- error("a one-bar meter cannot go on % or ...", rest);
285
- continue;
286
- }
287
- if (list.length === 1 && !meter && list[0] === "%") {
288
- cells.push({ kind: "simile" });
289
- continue;
290
- }
291
- if (list.length === 1 && !meter && FERMATA.has(list[0] ?? "")) {
292
- cells.push({ kind: "fermata" });
293
- continue;
294
- }
295
- const slots = [];
296
- for (const token of list) {
297
- const parts = groupMembers(token);
298
- if (parts.length === 1) {
299
- const s = simple(token);
300
- if (s)
301
- slots.push(s);
302
- continue;
303
- }
304
- const members = [];
305
- for (const m of parts) {
306
- if (!m)
307
- error("an empty member in a group", token);
308
- else {
309
- const s = simple(m);
310
- if (s)
311
- members.push(s);
312
- }
313
- }
314
- slots.push({ kind: "group", members });
315
- }
316
- cells.push({ kind: "slots", meter, slots });
317
- }
484
+ const cells = parts.map(readCell).filter((c) => c !== null);
318
485
  const failed = diagnostics.some((d) => d.severity === "error");
319
486
  return {
320
487
  bars: failed ? null : { kind: "bars", line, opens, closes, cells, repeat, ending },
@@ -27,6 +27,23 @@ function uneven(slots, meter, line) {
27
27
  token: `${slots}`,
28
28
  };
29
29
  }
30
+ const PUSH_MARKS = { eighth: "<", sixteenth: "<<" };
31
+ const PUSH_LENGTH = { eighth: 1 / 8, sixteenth: 1 / 16 };
32
+ /** Each simple slot of a bar, in order, with how long it lasts in whole notes. */
33
+ function timed(bar) {
34
+ const each = bar.meter.n / bar.meter.d / bar.slots.length;
35
+ return bar.slots.flatMap((s) => s.kind === "group"
36
+ ? s.members.map((m) => ({ slot: m, length: each / s.members.length }))
37
+ : [{ slot: s, length: each }]);
38
+ }
39
+ /** Why a push can't take its time from a slot this long; null when it can. */
40
+ function pushProblem(push, before) {
41
+ if (before === null)
42
+ return "a push takes its time from the slot before it, and nothing plays before this one; write a pickup bar";
43
+ return PUSH_LENGTH[push] > before + 1e-9
44
+ ? `${push === "eighth" ? "an eighth" : "a sixteenth"} push is longer than the slot before it`
45
+ : null;
46
+ }
30
47
  const normalize = (name) => name.toLowerCase().replace(/\s+/g, " ").trim();
31
48
  const isWritten = (s) => s.lines.some((l) => l.kind === "bars" || l.kind === "invalid");
32
49
  /** Grammar §6: an empty section that matches nothing, and how to fix it. */
@@ -85,39 +102,65 @@ export function expand(lines) {
85
102
  const resolved = new Map();
86
103
  let previous = null;
87
104
  let written = 0;
105
+ /** A rehearsal mark waiting for the bar after it (grammar 2.5). */
106
+ const pending = { mark: null };
107
+ /** The bar as written, with the mark before it and its own words. */
108
+ const marked = (bar, words) => {
109
+ const out = { ...bar };
110
+ if (pending.mark)
111
+ out.rehearsal = pending.mark.label;
112
+ if (words)
113
+ out.words = words;
114
+ pending.mark = null;
115
+ return out;
116
+ };
117
+ const markBar = (c, line) => {
118
+ if (pending.mark)
119
+ error(line, "two rehearsal marks on one bar", `@${c.label}`);
120
+ pending.mark = { label: c.label, line };
121
+ return null;
122
+ };
123
+ const simile = (c, line) => {
124
+ if (!previous)
125
+ error(line, "% has no bar before it to repeat", "%");
126
+ const meter = previous?.meter ?? null;
127
+ const slots = previous?.slots ?? [{ kind: "hold" }];
128
+ return marked({ kind: "bar", meter, slots, own: false, written: ++written }, c.words);
129
+ };
130
+ const ownBar = (c, line) => {
131
+ const first = c.slots[0];
132
+ const head = first?.kind === "group" ? first.members[0] : first;
133
+ if (!previous && head?.kind === "hold")
134
+ error(line, "/ has nothing before it to hold", "/");
135
+ previous = { meter: c.meter, slots: c.slots };
136
+ const bar = {
137
+ kind: "bar",
138
+ meter: c.meter,
139
+ slots: c.slots,
140
+ own: true,
141
+ written: ++written,
142
+ };
143
+ return marked(bar, c.words);
144
+ };
145
+ const resolveCell = (c, line) => {
146
+ if (c.kind === "fermata")
147
+ return { kind: "fermata" };
148
+ if (c.kind === "direction")
149
+ return c;
150
+ if (c.kind === "rehearsal")
151
+ return markBar(c, line);
152
+ return c.kind === "simile" ? simile(c, line) : ownBar(c, line);
153
+ };
88
154
  for (const l of sections.flatMap((s) => s.lines)) {
89
155
  if (l.kind === "invalid")
90
156
  written += l.written;
91
157
  if (l.kind !== "bars")
92
158
  continue;
93
- const cells = [];
94
- for (const c of l.cells) {
95
- if (c.kind === "fermata")
96
- cells.push({ kind: "fermata" });
97
- else if (c.kind === "direction")
98
- cells.push(c);
99
- else if (c.kind === "simile") {
100
- if (!previous)
101
- error(l.line, "% has no bar before it to repeat", "%");
102
- cells.push({
103
- kind: "bar",
104
- meter: previous?.meter ?? null,
105
- slots: previous?.slots ?? [{ kind: "hold" }],
106
- own: false,
107
- written: ++written,
108
- });
109
- }
110
- else {
111
- const first = c.slots[0];
112
- const head = first?.kind === "group" ? first.members[0] : first;
113
- if (!previous && head?.kind === "hold")
114
- error(l.line, "/ has nothing before it to hold", "/");
115
- cells.push({ kind: "bar", meter: c.meter, slots: c.slots, own: true, written: ++written });
116
- previous = { meter: c.meter, slots: c.slots };
117
- }
118
- }
119
- resolved.set(l, cells);
159
+ resolved.set(l, l.cells.map((c) => resolveCell(c, l.line)).filter((p) => p !== null));
120
160
  }
161
+ const unused = pending.mark;
162
+ if (unused)
163
+ error(unused.line, "a rehearsal mark marks the bar after it; none follows", `@${unused.label}`);
121
164
  // Pair |: and :| within each section, with any endings.
122
165
  const itemsOf = new Map(sections.map((s) => [s, pairRepeats(s.lines, error)]));
123
166
  const plan = planJump(lines, error);
@@ -209,8 +252,25 @@ export function expand(lines) {
209
252
  feel,
210
253
  ...(swingPercent === undefined ? {} : { swingPercent }),
211
254
  slots: p.slots,
255
+ ...(p.rehearsal === undefined ? {} : { rehearsal: p.rehearsal }),
256
+ ...(p.words === undefined ? {} : { words: p.words }),
212
257
  };
213
258
  };
259
+ /** How long the slot played just before is, in whole notes; null after a fermata or at the start. */
260
+ const before = { length: null };
261
+ const pushReported = new Set();
262
+ /** Each push takes its time from the slot played just before it (grammar 2.8). */
263
+ const checkPushes = (bar) => {
264
+ for (const { slot, length } of timed(bar)) {
265
+ const problem = slot.push && pushProblem(slot.push, before.length);
266
+ const key = `${bar.line}\u0000${problem}`;
267
+ if (problem && !pushReported.has(key)) {
268
+ pushReported.add(key);
269
+ error(bar.line, problem, PUSH_MARKS[slot.push ?? "eighth"]);
270
+ }
271
+ before.length = length;
272
+ }
273
+ };
214
274
  const emit = (p, line, out) => {
215
275
  if (stopped())
216
276
  return;
@@ -220,12 +280,16 @@ export function expand(lines) {
220
280
  return;
221
281
  if (++work > MAX_WORK)
222
282
  return stop(line);
223
- if (p.kind === "fermata")
283
+ if (p.kind === "fermata") {
284
+ before.length = null;
224
285
  return void out.push({ kind: "fermata", line });
286
+ }
225
287
  if (count >= MAX_EXPANDED_BARS)
226
288
  return stop(line);
227
289
  count++;
228
- out.push({ kind: "bar", bar: barOf(p, line) });
290
+ const bar = barOf(p, line);
291
+ checkPushes(bar);
292
+ out.push({ kind: "bar", bar });
229
293
  };
230
294
  /** Play `body` `repeat` times into `out`; an open repeat plays one pass inside an open event. */
231
295
  const times = (repeat, line, out, body) => {
@@ -10,7 +10,7 @@ import type { Cell, ChartParse, Line, Slot } from "./types.js";
10
10
  export declare function reduceSlots(slots: Slot[], beats?: number): Slot[];
11
11
  /** A slot in canonical spelling; a group's members are joined with `_`. */
12
12
  export declare function printSlot(s: Slot): string;
13
- /** A cell in canonical form: `%`, `...`, or an optional `[n/d]` and the fewest slots. */
13
+ /** A cell in canonical form: `%`, `...`, a mark, or an optional `[n/d]` and the fewest slots, with any words. */
14
14
  export declare function printCell(c: Cell, beats?: number): string;
15
15
  /** An ending's passes as printed after its `|`: in order, runs of three or more as a range (`1-3`, `1,2`, `1,3-5`). */
16
16
  export declare function printPasses(passes: number[]): string;
@@ -7,7 +7,7 @@ function continues(sounding, s) {
7
7
  if (s.kind === "hold")
8
8
  return true;
9
9
  if (s.kind === "silence" || s.kind === "nc")
10
- return sounding?.kind === s.kind;
10
+ return !s.push && sounding?.kind === s.kind;
11
11
  return false;
12
12
  }
13
13
  /**
@@ -41,23 +41,49 @@ export function reduceSlots(slots, beats) {
41
41
  return slots;
42
42
  }
43
43
  const SYMBOLS = { hold: "/", nc: "N.C.", silence: "--", unknown: "?" };
44
+ const PUSHES = { eighth: "<", sixteenth: "<<" };
45
+ const ARTICULATIONS = { accent: ">", hit: "^" };
46
+ /** A slot's leading marks: its push, then its articulation (grammar 2.7, 2.8). */
47
+ function printMarks(s) {
48
+ const push = "push" in s && s.push ? PUSHES[s.push] : "";
49
+ return push + (s.kind === "chord" && s.articulation ? ARTICULATIONS[s.articulation] : "");
50
+ }
44
51
  function printSimple(s) {
45
- return s.kind === "chord" ? s.chord.canonical : SYMBOLS[s.kind];
52
+ const body = s.kind === "chord" ? s.chord.canonical + (s.voicing?.canonical ?? "") : SYMBOLS[s.kind];
53
+ return printMarks(s) + body;
46
54
  }
47
55
  /** A slot in canonical spelling; a group's members are joined with `_`. */
48
56
  export function printSlot(s) {
49
57
  return s.kind === "group" ? s.members.map(printSimple).join("_") : printSimple(s);
50
58
  }
51
- /** A cell in canonical form: `%`, `...`, or an optional `[n/d]` and the fewest slots. */
59
+ /** Each slot with the words written before it, and any words after the last. */
60
+ function withWords(slots, words = []) {
61
+ const said = (at) => words.filter((w) => w.at === at).map((w) => `"${w.text}"`);
62
+ return [...slots.flatMap((s, i) => [...said(i), s]), ...said(slots.length)].join(" ");
63
+ }
64
+ /** The fewest slots, unless merging them would lose the place of some words. */
65
+ function reduceWithWords(slots, words, beats) {
66
+ const reduced = reduceSlots(slots, beats);
67
+ const size = slots.length / reduced.length;
68
+ if (!words)
69
+ return [reduced, []];
70
+ if (words.some((w) => w.at % size !== 0))
71
+ return [slots, words];
72
+ return [reduced, words.map((w) => ({ ...w, at: w.at / size }))];
73
+ }
74
+ /** A cell in canonical form: `%`, `...`, a mark, or an optional `[n/d]` and the fewest slots, with any words. */
52
75
  export function printCell(c, beats) {
53
76
  if (c.kind === "simile")
54
- return "%";
77
+ return withWords(["%"], c.words);
55
78
  if (c.kind === "fermata")
56
79
  return "...";
57
80
  if (c.kind === "direction")
58
81
  return printDirection(c.direction);
82
+ if (c.kind === "rehearsal")
83
+ return `@${c.label}`;
59
84
  const meter = c.meter ? `[${c.meter.n}/${c.meter.d}] ` : "";
60
- return meter + reduceSlots(c.slots, beats).map(printSlot).join(" ");
85
+ const [slots, words] = reduceWithWords(c.slots, c.words, beats);
86
+ return meter + withWords(slots.map(printSlot), words);
61
87
  }
62
88
  /** An ending's passes as printed after its `|`: in order, runs of three or more as a range (`1-3`, `1,2`, `1,3-5`). */
63
89
  export function printPasses(passes) {
@@ -100,7 +100,14 @@ function moveChord(chord, move, warn) {
100
100
  return r.ok ? r.value : chord;
101
101
  }
102
102
  function moveCells(cells, move, warn) {
103
- const simple = (s) => s.kind === "chord" ? { kind: "chord", chord: moveChord(s.chord, move, warn) } : s;
103
+ const simple = (s) => {
104
+ if (s.kind !== "chord")
105
+ return s;
106
+ const chord = moveChord(s.chord, move, warn);
107
+ return s.voicing
108
+ ? { ...s, chord, voicing: moveNoteSet(s.voicing, move, warn) }
109
+ : { ...s, chord };
110
+ };
104
111
  const slot = (s) => s.kind === "group" ? { kind: "group", members: s.members.map(simple) } : simple(s);
105
112
  return cells.map((c) => (c.kind === "slots" ? { ...c, slots: c.slots.map(slot) } : c));
106
113
  }
@@ -39,16 +39,33 @@ export type Directives = {
39
39
  */
40
40
  swingPercent?: number;
41
41
  };
42
- /** A chord slot holds a chord symbol or a note set; `chord.kind` tells which. */
42
+ /** `>` accents a chord; `^` makes it a hit, short and accented (grammar 2.7). */
43
+ export type Articulation = "accent" | "hit";
44
+ /**
45
+ * How early a slot arrives (grammar 2.8): `<` an eighth note, `<<` a
46
+ * sixteenth, taken from the slot played just before it.
47
+ */
48
+ export type Push = "eighth" | "sixteenth";
49
+ /**
50
+ * A chord slot holds a chord symbol or a note set; `chord.kind` tells
51
+ * which. `voicing` is the exact notes written after a chord's name
52
+ * (`Cmaj7{E3 G3 B3}`, grammar 4.2). The optional fields are present only
53
+ * when written.
54
+ */
43
55
  export type SimpleSlot = {
44
56
  kind: "chord";
45
57
  chord: ChordRecord;
58
+ voicing?: ChordRecord;
59
+ articulation?: Articulation;
60
+ push?: Push;
46
61
  } | {
47
62
  kind: "hold";
48
63
  } | {
49
64
  kind: "nc";
65
+ push?: Push;
50
66
  } | {
51
67
  kind: "silence";
68
+ push?: Push;
52
69
  } | {
53
70
  kind: "unknown";
54
71
  };
@@ -74,18 +91,37 @@ export type Direction = {
74
91
  to: "start" | "segno";
75
92
  al: "fine" | "coda" | null;
76
93
  };
77
- /** `meter` is a one-bar `[n/d]` override. `...` and a direction are not bars. */
94
+ /**
95
+ * Quoted words on a bar (grammar 2.6), placed before the slot numbered
96
+ * `at` (0-based); `at` equal to the slot count places them after the last
97
+ * slot. They carry no musical meaning.
98
+ */
99
+ export type Words = {
100
+ text: string;
101
+ at: number;
102
+ };
103
+ /**
104
+ * `meter` is a one-bar `[n/d]` override. `...`, a direction and a
105
+ * rehearsal mark are not bars. `words` is present only when written.
106
+ */
78
107
  export type Cell = {
79
108
  kind: "slots";
80
109
  meter: Meter | null;
81
110
  slots: Slot[];
111
+ words?: Words[];
82
112
  } | {
83
113
  kind: "simile";
114
+ words?: Words[];
84
115
  } | {
85
116
  kind: "fermata";
86
117
  } | {
87
118
  kind: "direction";
88
119
  direction: Direction;
120
+ }
121
+ /** `@B`: a mark on the bar after it (grammar 2.5). */
122
+ | {
123
+ kind: "rehearsal";
124
+ label: string;
89
125
  };
90
126
  export type Repeat = number | "open" | null;
91
127
  export type Line = {
@@ -153,6 +189,10 @@ export type PlayedBar = {
153
189
  swingPercent?: number;
154
190
  /** `%` resolved to the copied slots; holds stay holds. */
155
191
  slots: Slot[];
192
+ /** The rehearsal mark written just before this bar (`@B` gives "B"); absent when none. */
193
+ rehearsal?: string;
194
+ /** Words written on this bar; absent when none. `%` copies chords, not words. */
195
+ words?: Words[];
156
196
  };
157
197
  /** An open repeat shows one pass; the number of passes is unknown. */
158
198
  export type ChartEvent = {
@@ -1,7 +1,7 @@
1
1
  import { formatInterval, intervalBetween, intervalKey, parseInterval, transpose, } from "./intervals.js";
2
2
  import { printSuffix } from "./print.js";
3
3
  import { enumerateSuffixes, intervalSetKey } from "./suffixes.js";
4
- import { byDegree, chordIntervals, HARTE_SHORTHANDS } from "./vocabulary.js";
4
+ import { byDegree, chordIntervals, HARTE_SHORTHANDS, isOmission, } from "./vocabulary.js";
5
5
  /**
6
6
  * The Harte label for a parsed chord or note set: the largest shorthand
7
7
  * contained in the chord, the remaining intervals in parentheses, and the
@@ -10,7 +10,8 @@ import { byDegree, chordIntervals, HARTE_SHORTHANDS } from "./vocabulary.js";
10
10
  */
11
11
  export function toHarte(r) {
12
12
  const root = r.root ?? r.bass;
13
- const keys = new Set(r.intervals.map(intervalKey));
13
+ const left = omitted(r);
14
+ const keys = new Set([...r.intervals, ...left].map(intervalKey));
14
15
  const written = new Set(r.intervals.map(formatInterval));
15
16
  // Most intervals wins; ties go to the shorthand naming more degrees exactly as
16
17
  // written (sus4 over sus2 in a 9sus4, whose 9 only shares the 2's pitch class).
@@ -26,10 +27,21 @@ export function toHarte(r) {
26
27
  }
27
28
  const { name: shorthand, used } = best;
28
29
  const added = r.intervals.filter((i) => !used.has(intervalKey(i))).sort(byDegree);
29
- const list = added.length ? `(${added.map(formatInterval).join(",")})` : "";
30
+ // Harte marks a tone its shorthand has and the chord leaves out with `*` (`C:7(*3)`).
31
+ const out = left.filter((i) => used.has(intervalKey(i))).map((i) => `*${formatInterval(i)}`);
32
+ const items = [...added.map(formatInterval), ...out];
33
+ const list = items.length ? `(${items.join(",")})` : "";
30
34
  const bass = r.bass === root ? "" : `/${formatInterval(intervalBetween(root, r.bass))}`;
31
35
  return `${root}:${shorthand}${list}${bass}`;
32
36
  }
37
+ /** The intervals a chord's `no3`/`no5` leave out, so its label can name them. */
38
+ function omitted(r) {
39
+ if (!r.parts?.tones.some(isOmission))
40
+ return [];
41
+ const kept = { ...r.parts, tones: r.parts.tones.filter((t) => !isOmission(t)) };
42
+ const keys = new Set(r.intervals.map(intervalKey));
43
+ return chordIntervals(kept, "").intervals.filter((i) => !keys.has(intervalKey(i)));
44
+ }
33
45
  const shape = (quality, extension = null, tones = [], sus = null) => ({ quality, extension, sus, tones });
34
46
  const INTENDED = {
35
47
  maj: shape(""),
@@ -1,7 +1,7 @@
1
1
  import { toHarte } from "./harte.js";
2
2
  import { noteSemitone, transpose } from "./intervals.js";
3
3
  import { canonicalParts, printChord } from "./print.js";
4
- import { ALIASES, chordIntervals, EXTENSIONS, rejection, TONES, validateParts, } from "./vocabulary.js";
4
+ import { ALIASES, chordIntervals, EXTENSIONS, isOmission, OMISSIONS, rejection, TONES, validateParts, } from "./vocabulary.js";
5
5
  const ROOT = /^[A-G][#b]?/;
6
6
  const INLINE_ALTERATION = /^(b5|#5|b9|#9|#11|b13)/;
7
7
  /** Splits a symbol into its parts, or names the text it could not read. */
@@ -45,8 +45,9 @@ function tokenize(symbol) {
45
45
  const paren = /^\(([^)]*)\)/.exec(rest);
46
46
  if (paren) {
47
47
  for (const t of (paren[1] ?? "").split(",").map((x) => x.trim())) {
48
- if (!TONES.includes(t))
49
- return `"${t}" is not a tone a parenthesis can add`;
48
+ const problem = toneProblem(t, tones);
49
+ if (problem)
50
+ return problem;
50
51
  tones.push(t);
51
52
  }
52
53
  rest = rest.slice(paren[0].length);
@@ -61,6 +62,43 @@ function tokenize(symbol) {
61
62
  return `cannot read "${rest}"`;
62
63
  return { root, quality, extension: ext, sus, tones, bass };
63
64
  }
65
+ /** Why a tone can't go in a chord's parentheses after `before`; null when it can. */
66
+ function toneProblem(tone, before) {
67
+ if (isOmission(tone)) {
68
+ if (!OMISSIONS.includes(tone))
69
+ return `"${tone}": a chord leaves out only its 3rd or 5th (no3, no5)`;
70
+ return before.includes(tone) ? `${tone} is written twice` : null;
71
+ }
72
+ return TONES.includes(tone) ? null : `"${tone}" is not a tone a parenthesis can add`;
73
+ }
74
+ const ORDINAL = { 3: "3rd", 5: "5th" };
75
+ /**
76
+ * The intervals once `no3`/`no5` leave out a tone, or why they can't: the
77
+ * chord must have that tone, unaltered by its own parentheses.
78
+ */
79
+ function omit(intervals, parts, symbol) {
80
+ let out = intervals;
81
+ for (const tone of parts.tones.filter(isOmission)) {
82
+ const degree = Number(tone.slice(2));
83
+ const fail = (why) => ({ message: `${symbol}: ${why}`, token: symbol });
84
+ const altered = parts.tones.some((t) => !isOmission(t) && Number(t.replace(/^[#b]/, "")) === degree && /^[#b]/.test(t));
85
+ if (altered)
86
+ return fail(`the ${ORDINAL[degree]} is altered and left out`);
87
+ if (!out.some((i) => i.degree === degree)) {
88
+ const base = printChord({ ...parts, tones: parts.tones.filter((t) => !isOmission(t)) });
89
+ return fail(`${base} has no ${ORDINAL[degree]} to leave out`);
90
+ }
91
+ out = out.filter((i) => i.degree !== degree);
92
+ }
93
+ return out;
94
+ }
95
+ /** A triad with no third is the power chord: `C(no3)` is `C5`, one spelling (grammar 3). */
96
+ function powerChord(parts) {
97
+ const triad = (parts.quality === "" || parts.quality === "m") && !parts.extension && !parts.sus;
98
+ if (!triad || !parts.tones.includes("no3"))
99
+ return parts;
100
+ return { ...parts, quality: "5", tones: parts.tones.filter((t) => t !== "no3") };
101
+ }
64
102
  /**
65
103
  * Logic Pro's spellings (Appendix A.5): groups in a row are one list
66
104
  * (`(5)(7)` is `(5,7)`), and `5` in a bare root's group is the power chord
@@ -86,6 +124,8 @@ function normalizeSymbol(symbol) {
86
124
  for (const [pattern, replacement] of ALIASES)
87
125
  rest = rest.replace(pattern, replacement);
88
126
  rest = logicGroups(rest);
127
+ // `(omit3)` and `(omit 3)` are `(no3)`.
128
+ rest = rest.replace(/(?<=[(,]\s*)omit\s*(\d+)(?=\s*[,)])/g, "no$1");
89
129
  // `(add9)` is `(9)`: inside a group, `add` before a tone it may add is dropped.
90
130
  rest = rest.replace(/(?<=[(,]\s*)add(2|4|9|11)(?=\s*[,)])/g, "$1");
91
131
  // A bare `add9` outside any group; what is left inside one is the tokenizer's to name.
@@ -108,14 +148,19 @@ export function parseChord(symbol) {
108
148
  const normal = normalizeSymbol(symbol);
109
149
  if (!("text" in normal))
110
150
  return { ok: false, error: normal };
111
- const parts = tokenize(normal.text);
112
- if (typeof parts === "string") {
113
- return { ok: false, error: { message: `${symbol}: ${parts}`, token: symbol } };
151
+ const read = tokenize(normal.text);
152
+ if (typeof read === "string") {
153
+ return { ok: false, error: { message: `${symbol}: ${read}`, token: symbol } };
114
154
  }
155
+ const parts = powerChord(read);
115
156
  const invalid = validateParts(parts, symbol);
116
157
  if (invalid)
117
158
  return { ok: false, error: invalid };
118
- const { intervals, warnings, alteredOpen } = chordIntervals(parts, symbol);
159
+ const added = chordIntervals({ ...parts, tones: parts.tones.filter((t) => !isOmission(t)) }, symbol);
160
+ const { warnings, alteredOpen } = added;
161
+ const intervals = omit(added.intervals, parts, symbol);
162
+ if (!Array.isArray(intervals))
163
+ return { ok: false, error: intervals };
119
164
  const pitches = intervals.map((i) => transpose(parts.root, i));
120
165
  if (parts.bass && !pitches.includes(parts.bass))
121
166
  pitches.push(parts.bass);
@@ -1,6 +1,9 @@
1
- import { byDegree, toneInterval } from "./vocabulary.js";
2
- /** The tones in canonical order (by degree), as the canonical spelling lists them. */
3
- const sortTones = (tones) => [...tones].sort((a, b) => byDegree(toneInterval(a), toneInterval(b)));
1
+ import { byDegree, isOmission, toneInterval } from "./vocabulary.js";
2
+ /** The tones in canonical order: added tones by degree, then what is left out (`(b9,no5)`). */
3
+ const sortTones = (tones) => [
4
+ ...tones.filter((t) => !isOmission(t)).sort((a, b) => byDegree(toneInterval(a), toneInterval(b))),
5
+ ...tones.filter(isOmission).sort(),
6
+ ];
4
7
  /** The parts as the canonical spelling has them: the same parts, tones sorted. */
5
8
  export function canonicalParts(parts) {
6
9
  return { ...parts, tones: sortTones(parts.tones) };
@@ -18,6 +18,9 @@ export declare const VALID_EXTENSIONS: Record<Quality, (Extension | null)[]>;
18
18
  export declare const SUS_ALLOWED_WITH: (Extension | null)[];
19
19
  /** Tones a parenthesis may hold. Tone `7` means the interval b7. */
20
20
  export declare const TONES: string[];
21
+ /** Tones a parenthesis may leave out (grammar 3): the 3rd or the 5th. */
22
+ export declare const OMISSIONS: string[];
23
+ export declare const isOmission: (tone: string) => boolean;
21
24
  export declare const toneInterval: (tone: string) => Interval;
22
25
  /** Degree order, then flat before natural before sharp. */
23
26
  export declare const byDegree: (a: Interval, b: Interval) => number;
@@ -41,6 +41,9 @@ export const VALID_EXTENSIONS = {
41
41
  export const SUS_ALLOWED_WITH = [null, "7", "9", "13"];
42
42
  /** Tones a parenthesis may hold. Tone `7` means the interval b7. */
43
43
  export const TONES = ["2", "4", "6", "7", "9", "11", "13", "b5", "#5", "b9", "#9", "#11", "b13"];
44
+ /** Tones a parenthesis may leave out (grammar 3): the 3rd or the 5th. */
45
+ export const OMISSIONS = ["no3", "no5"];
46
+ export const isOmission = (tone) => tone.startsWith("no");
44
47
  export const toneInterval = (tone) => {
45
48
  const i = parseInterval(tone === "7" ? "b7" : tone);
46
49
  if (!i)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barmark",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "Markdown-inspired plain-text notation for chord charts: a parser, a canonical printer and Harte-label conversion.",
5
5
  "type": "module",
6
6
  "exports": {