barmark 0.10.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.
@@ -1,8 +1,49 @@
1
+ import { planJump } from "./direction.js";
1
2
  import { beatsOf } from "./directives.js";
3
+ import { pairRepeats } from "./repeats.js";
2
4
  /** Nested repeats multiply; expansion stops here rather than run away. */
3
5
  export const MAX_EXPANDED_BARS = 10_000;
4
6
  /** Repeats of bodies that play no bars (fermatas only) are bounded too. */
5
7
  const MAX_WORK = MAX_EXPANDED_BARS * 10;
8
+ /**
9
+ * How each mark moves play along. A mark the jump does not use is an error
10
+ * that drops the jump, so with a jump planned every mark here applies.
11
+ */
12
+ const NEXT = {
13
+ main: { jump: "jumped" },
14
+ "seek segno": { segno: "return" },
15
+ "seek coda": { coda: "return" },
16
+ return: { fine: "done", "to coda": "seek coda" },
17
+ };
18
+ /** The warning for a cell whose slots divide its beats unevenly (grammar 2.1). */
19
+ function uneven(slots, meter, line) {
20
+ const b = beatsOf(meter);
21
+ if (b % slots === 0 || slots % b === 0)
22
+ return null;
23
+ return {
24
+ line,
25
+ severity: "warning",
26
+ message: `${slots} slots divide ${b} beats unevenly`,
27
+ token: `${slots}`,
28
+ };
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
+ }
6
47
  const normalize = (name) => name.toLowerCase().replace(/\s+/g, " ").trim();
7
48
  const isWritten = (s) => s.lines.some((l) => l.kind === "bars" || l.kind === "invalid");
8
49
  /** Grammar §6: an empty section that matches nothing, and how to fix it. */
@@ -40,7 +81,16 @@ function removeLastBar(events) {
40
81
  */
41
82
  export function expand(lines) {
42
83
  const diagnostics = [];
43
- const error = (line, message, token) => diagnostics.push({ line, severity: "error", message, token });
84
+ // The return after a jump plays sections again: it reports only what the first pass did not.
85
+ const reported = new Set();
86
+ let again = false;
87
+ const error = (line, message, token) => {
88
+ const key = `${line}\u0000${message}`;
89
+ if (again && reported.has(key))
90
+ return;
91
+ reported.add(key);
92
+ diagnostics.push({ line, severity: "error", message, token });
93
+ };
44
94
  const sections = [{ heading: null, lines: [] }];
45
95
  for (const l of lines) {
46
96
  if (l.kind === "section")
@@ -52,86 +102,77 @@ export function expand(lines) {
52
102
  const resolved = new Map();
53
103
  let previous = null;
54
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
+ };
55
154
  for (const l of sections.flatMap((s) => s.lines)) {
56
155
  if (l.kind === "invalid")
57
156
  written += l.written;
58
157
  if (l.kind !== "bars")
59
158
  continue;
60
- const cells = [];
61
- for (const c of l.cells) {
62
- if (c.kind === "fermata")
63
- cells.push({ kind: "fermata" });
64
- else if (c.kind === "simile") {
65
- if (!previous)
66
- error(l.line, "% has no bar before it to repeat", "%");
67
- cells.push({
68
- kind: "bar",
69
- meter: previous?.meter ?? null,
70
- slots: previous?.slots ?? [{ kind: "hold" }],
71
- own: false,
72
- written: ++written,
73
- });
74
- }
75
- else {
76
- const first = c.slots[0];
77
- const head = first?.kind === "group" ? first.members[0] : first;
78
- if (!previous && head?.kind === "hold")
79
- error(l.line, "/ has nothing before it to hold", "/");
80
- cells.push({ kind: "bar", meter: c.meter, slots: c.slots, own: true, written: ++written });
81
- previous = { meter: c.meter, slots: c.slots };
82
- }
83
- }
84
- resolved.set(l, cells);
159
+ resolved.set(l, l.cells.map((c) => resolveCell(c, l.line)).filter((p) => p !== null));
85
160
  }
86
- // Pair |: and :| within each section.
87
- const itemsOf = new Map();
88
- for (const s of sections) {
89
- const items = [];
90
- let open = null;
91
- for (const l of s.lines) {
92
- const bars = l.kind === "bars" ? l : null;
93
- if (bars?.opens) {
94
- if (open)
95
- error(bars.line, "|: inside another |:", "|:");
96
- else
97
- open = { line: bars.line, entries: [] };
98
- }
99
- if (bars?.closes) {
100
- if (!open) {
101
- error(bars.line, ":| has no |: before it in this section", ":|");
102
- items.push({ kind: "line", line: bars, repeat: null });
103
- continue;
104
- }
105
- open.entries.push({ line: bars, repeat: null });
106
- items.push({
107
- kind: "bracket",
108
- line: open.line,
109
- entries: open.entries,
110
- repeat: bars.repeat ?? 2,
111
- });
112
- open = null;
113
- continue;
114
- }
115
- const entry = { line: l, repeat: bars?.repeat ?? null };
116
- if (open)
117
- open.entries.push(entry);
118
- else
119
- items.push({ kind: "line", ...entry });
120
- }
121
- if (open) {
122
- error(open.line, "|: is never closed in this section", "|:");
123
- items.push(...open.entries.map((e) => ({ kind: "line", ...e })));
124
- }
125
- itemsOf.set(s, items);
126
- }
127
- const state = {
161
+ const unused = pending.mark;
162
+ if (unused)
163
+ error(unused.line, "a rehearsal mark marks the bar after it; none follows", `@${unused.label}`);
164
+ // Pair |: and :| within each section, with any endings.
165
+ const itemsOf = new Map(sections.map((s) => [s, pairRepeats(s.lines, error)]));
166
+ const plan = planJump(lines, error);
167
+ const start = () => ({
128
168
  key: null,
129
169
  time: { n: 4, d: 4 },
130
170
  tempo: null,
131
171
  change: null,
132
172
  feel: "straight",
133
173
  swingPercent: undefined,
134
- };
174
+ });
175
+ const state = start();
135
176
  const warned = new Set();
136
177
  const warn = (line, message, token) => {
137
178
  if (warned.has(line))
@@ -180,48 +221,75 @@ export function expand(lines) {
180
221
  error(line, `expansion stopped at ${MAX_EXPANDED_BARS} bars`, "x");
181
222
  };
182
223
  let sectionName = null;
224
+ let phase = "main";
225
+ const stopped = () => capped || phase === "jumped" || phase === "done";
226
+ const jumped = () => phase === "jumped";
227
+ const seeking = () => phase === "seek segno" || phase === "seek coda";
228
+ /** The jump is taken once; after it, `To Coda` and `Fine` take effect. */
229
+ const direct = (d) => {
230
+ if (plan)
231
+ phase = NEXT[phase]?.[d.kind] ?? phase;
232
+ };
233
+ /** A bar as played now; its slot count is checked the first time a written bar plays. */
234
+ const barOf = (p, line) => {
235
+ const meter = p.meter ?? state.time;
236
+ if (p.own && !checked.has(p)) {
237
+ checked.add(p);
238
+ const warning = uneven(p.slots.length, meter, line);
239
+ if (warning)
240
+ diagnostics.push(warning);
241
+ }
242
+ const { key, tempo, change: tempoChange, feel, swingPercent } = state;
243
+ return {
244
+ index: 0,
245
+ written: p.written,
246
+ line,
247
+ section: sectionName,
248
+ meter,
249
+ key,
250
+ tempo,
251
+ tempoChange,
252
+ feel,
253
+ ...(swingPercent === undefined ? {} : { swingPercent }),
254
+ slots: p.slots,
255
+ ...(p.rehearsal === undefined ? {} : { rehearsal: p.rehearsal }),
256
+ ...(p.words === undefined ? {} : { words: p.words }),
257
+ };
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
+ };
183
274
  const emit = (p, line, out) => {
184
- if (capped)
275
+ if (stopped())
276
+ return;
277
+ if (p.kind === "direction")
278
+ return direct(p.direction);
279
+ if (seeking())
185
280
  return;
186
281
  if (++work > MAX_WORK)
187
282
  return stop(line);
188
283
  if (p.kind === "fermata") {
189
- out.push({ kind: "fermata", line });
190
- return;
284
+ before.length = null;
285
+ return void out.push({ kind: "fermata", line });
191
286
  }
192
287
  if (count >= MAX_EXPANDED_BARS)
193
288
  return stop(line);
194
289
  count++;
195
- const meter = p.meter ?? state.time;
196
- if (p.own && !checked.has(p)) {
197
- checked.add(p);
198
- const k = p.slots.length;
199
- const b = beatsOf(meter);
200
- if (b % k !== 0 && k % b !== 0)
201
- diagnostics.push({
202
- line,
203
- severity: "warning",
204
- message: `${k} slots divide ${b} beats unevenly`,
205
- token: `${k}`,
206
- });
207
- }
208
- const { key, tempo, change: tempoChange, feel, swingPercent } = state;
209
- out.push({
210
- kind: "bar",
211
- bar: {
212
- index: 0,
213
- written: p.written,
214
- line,
215
- section: sectionName,
216
- meter,
217
- key,
218
- tempo,
219
- tempoChange,
220
- feel,
221
- ...(swingPercent === undefined ? {} : { swingPercent }),
222
- slots: p.slots,
223
- },
224
- });
290
+ const bar = barOf(p, line);
291
+ checkPushes(bar);
292
+ out.push({ kind: "bar", bar });
225
293
  };
226
294
  /** Play `body` `repeat` times into `out`; an open repeat plays one pass inside an open event. */
227
295
  const times = (repeat, line, out, body) => {
@@ -240,13 +308,17 @@ export function expand(lines) {
240
308
  out.push({ kind: "open", line, events: inner });
241
309
  return;
242
310
  }
243
- for (let i = 0; i < (repeat ?? 1) && !capped; i++) {
311
+ // After the jump every repeat plays once.
312
+ const passes = phase === "main" ? (repeat ?? 1) : 1;
313
+ for (let i = 0; i < passes && !stopped(); i++) {
244
314
  if (++work > MAX_WORK)
245
315
  return stop(line);
246
316
  body(out);
247
317
  }
248
318
  };
249
319
  const playLine = ({ line: l, repeat }, out) => {
320
+ if (stopped())
321
+ return;
250
322
  if (l.kind === "directive")
251
323
  apply(l.set, l.line);
252
324
  if (l.kind !== "bars")
@@ -260,6 +332,8 @@ export function expand(lines) {
260
332
  for (const it of items) {
261
333
  if (it.kind === "line")
262
334
  playLine(it, out);
335
+ else if (it.endings.length)
336
+ playEndings(it, out);
263
337
  else
264
338
  times(it.repeat, it.line, out, (into) => {
265
339
  for (const e of it.entries)
@@ -267,49 +341,87 @@ export function expand(lines) {
267
341
  });
268
342
  }
269
343
  };
344
+ /** Each pass plays the body, then its ending; after the jump, only the last pass. */
345
+ const playEndings = (it, out) => {
346
+ const highest = typeof it.repeat === "number" ? it.repeat : 1;
347
+ const first = phase === "main" ? 1 : highest;
348
+ for (let pass = first; pass <= highest && !stopped(); pass++) {
349
+ if (++work > MAX_WORK)
350
+ return stop(it.line);
351
+ for (const e of it.entries)
352
+ playLine(e, out);
353
+ const ending = it.endings.find((x) => x.passes.includes(pass));
354
+ if (ending)
355
+ playLine(ending.entry, out);
356
+ }
357
+ };
270
358
  const events = [];
271
359
  const occurrences = [];
272
360
  const definitions = new Map();
273
- for (const s of sections) {
274
- const h = s.heading;
275
- const items = itemsOf.get(s) ?? [];
276
- if (!h) {
277
- sectionName = null;
278
- playItems(items, events);
279
- continue;
280
- }
281
- sectionName = h.name;
282
- const out = [];
283
- const isDefinition = isWritten(s);
284
- let replayOf = null;
285
- if (isDefinition) {
286
- definitions.set(normalize(h.name), s);
287
- if (h.elided)
288
- error(h.line, "-> is only for a replay; leave the bar out instead", "->");
289
- times(h.repeat, h.line, out, (into) => playItems(items, into));
361
+ /** Headings already played, so a written section played again by the jump is a replay. */
362
+ const heard = new Set();
363
+ const playSections = () => {
364
+ for (const s of sections) {
365
+ if (stopped())
366
+ return;
367
+ playSection(s);
290
368
  }
291
- else {
292
- // A nameless heading is already an error; it has nothing to replay.
293
- if (!h.name)
294
- continue;
295
- const source = definitions.get(normalize(h.name));
296
- if (!source?.heading) {
297
- error(h.line, unmatchedReplay(h, sections), h.name);
298
- continue;
299
- }
300
- replayOf = source.heading.line;
301
- const body = itemsOf.get(source) ?? [];
302
- times(h.repeat, h.line, out, (into) => playItems(body, into));
369
+ };
370
+ /** A written section's bars into `out`. */
371
+ const playWritten = (s, h, out) => {
372
+ definitions.set(normalize(h.name), s);
373
+ if (h.elided)
374
+ error(h.line, "-> is only for a replay; leave the bar out instead", "->");
375
+ times(h.repeat, h.line, out, (into) => playItems(itemsOf.get(s) ?? [], into));
376
+ return { replayOf: null, elided: false };
377
+ };
378
+ /** A replay's bars into `out`, then its own lines; null when it replays nothing. */
379
+ const playReplay = (s, h, out) => {
380
+ // A nameless heading is already an error; it has nothing to replay.
381
+ if (!h.name)
382
+ return null;
383
+ const source = definitions.get(normalize(h.name));
384
+ if (!source?.heading) {
385
+ error(h.line, unmatchedReplay(h, sections), h.name);
386
+ return null;
303
387
  }
304
- const elided = !isDefinition && h.elided && removeLastBar(out);
388
+ times(h.repeat, h.line, out, (into) => playItems(itemsOf.get(source) ?? [], into));
389
+ const elided = h.elided && removeLastBar(out);
305
390
  // A replay heading stands for its bars: its own lines (directives) come after them.
306
- if (!isDefinition)
307
- playItems(items, out);
308
- events.push(...out);
391
+ playItems(itemsOf.get(s) ?? [], out);
392
+ return { replayOf: source.heading.line, elided };
393
+ };
394
+ /** A section occurrence; one the jump plays again is a replay of itself. */
395
+ const record = (h, out, replayOf, elided) => {
396
+ // Sections the return passes over while seeking play nothing and are not occurrences.
397
+ if (phase !== "main" && phase !== "jumped" && !out.length)
398
+ return;
399
+ const of = replayOf ?? (heard.has(h.line) ? h.line : null);
400
+ heard.add(h.line);
309
401
  occurrences.push([
310
- { name: h.name, line: h.line, replayOf, firstBar: null, lastBar: null, elided },
402
+ { name: h.name, line: h.line, replayOf: of, firstBar: null, lastBar: null, elided },
311
403
  out,
312
404
  ]);
405
+ };
406
+ const playSection = (s) => {
407
+ const h = s.heading;
408
+ sectionName = h?.name ?? null;
409
+ if (!h)
410
+ return playItems(itemsOf.get(s) ?? [], events);
411
+ const out = [];
412
+ const played = isWritten(s) ? playWritten(s, h, out) : playReplay(s, h, out);
413
+ if (!played)
414
+ return;
415
+ events.push(...out);
416
+ record(h, out, played.replayOf, played.elided);
417
+ };
418
+ playSections();
419
+ if (jumped() && plan) {
420
+ // The return reads the chart again from the top, so the directives in force are the written ones.
421
+ Object.assign(state, start());
422
+ again = true;
423
+ phase = plan.to === "start" ? "return" : "seek segno";
424
+ playSections();
313
425
  }
314
426
  flattenBars(events).forEach((b, i) => {
315
427
  b.index = i + 1;
@@ -1,9 +1,10 @@
1
1
  export { parseBarLine } from "./barLine.js";
2
2
  export { degreeOf } from "./degree.js";
3
+ export { printDirection } from "./direction.js";
3
4
  export { beatsOf, DIRECTIVE_NAMES, parseDirectiveLine, parseMeter } from "./directives.js";
4
5
  export { readDocument } from "./document.js";
5
6
  export { expand, flattenBars, MAX_EXPANDED_BARS } from "./expand.js";
6
7
  export { parseChart } from "./parse.js";
7
- export { printCell, printChart, printLine, printParsed, printSlot, reduceSlots } from "./print.js";
8
+ export { printCell, printChart, printLine, printParsed, printPasses, printSlot, reduceSlots, } from "./print.js";
8
9
  export { type TransposeBy, transposeChart } from "./transpose.js";
9
10
  export type * from "./types.js";
@@ -1,8 +1,9 @@
1
1
  export { parseBarLine } from "./barLine.js";
2
2
  export { degreeOf } from "./degree.js";
3
+ export { printDirection } from "./direction.js";
3
4
  export { beatsOf, DIRECTIVE_NAMES, parseDirectiveLine, parseMeter } from "./directives.js";
4
5
  export { readDocument } from "./document.js";
5
6
  export { expand, flattenBars, MAX_EXPANDED_BARS } from "./expand.js";
6
7
  export { parseChart } from "./parse.js";
7
- export { printCell, printChart, printLine, printParsed, printSlot, reduceSlots } from "./print.js";
8
+ export { printCell, printChart, printLine, printParsed, printPasses, printSlot, reduceSlots, } from "./print.js";
8
9
  export { transposeChart } from "./transpose.js";
@@ -10,8 +10,10 @@ 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
+ /** 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
+ export declare function printPasses(passes: number[]): string;
15
17
  /**
16
18
  * One parsed line in canonical form. Text and invalid lines print as stored.
17
19
  * `beats` gives each cell's beat count where known, so reduction adds no warning.
@@ -1,3 +1,5 @@
1
+ import { isBar } from "./barLine.js";
2
+ import { printDirection } from "./direction.js";
1
3
  import { beatsOf } from "./directives.js";
2
4
  import { parseChart } from "./parse.js";
3
5
  /** A slot with no attack of its own continues whatever sounds before it. A repeated chord name is a re-attack. */
@@ -5,7 +7,7 @@ function continues(sounding, s) {
5
7
  if (s.kind === "hold")
6
8
  return true;
7
9
  if (s.kind === "silence" || s.kind === "nc")
8
- return sounding?.kind === s.kind;
10
+ return !s.push && sounding?.kind === s.kind;
9
11
  return false;
10
12
  }
11
13
  /**
@@ -39,21 +41,61 @@ export function reduceSlots(slots, beats) {
39
41
  return slots;
40
42
  }
41
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
+ }
42
51
  function printSimple(s) {
43
- 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;
44
54
  }
45
55
  /** A slot in canonical spelling; a group's members are joined with `_`. */
46
56
  export function printSlot(s) {
47
57
  return s.kind === "group" ? s.members.map(printSimple).join("_") : printSimple(s);
48
58
  }
49
- /** 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. */
50
75
  export function printCell(c, beats) {
51
76
  if (c.kind === "simile")
52
- return "%";
77
+ return withWords(["%"], c.words);
53
78
  if (c.kind === "fermata")
54
79
  return "...";
80
+ if (c.kind === "direction")
81
+ return printDirection(c.direction);
82
+ if (c.kind === "rehearsal")
83
+ return `@${c.label}`;
55
84
  const meter = c.meter ? `[${c.meter.n}/${c.meter.d}] ` : "";
56
- 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);
87
+ }
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`). */
89
+ export function printPasses(passes) {
90
+ const runs = [];
91
+ for (const p of passes) {
92
+ const run = runs.at(-1);
93
+ if (run && run.at(-1) === p - 1)
94
+ run.push(p);
95
+ else
96
+ runs.push([p]);
97
+ }
98
+ return runs.flatMap((r) => (r.length >= 3 ? [`${r[0]}-${r.at(-1)}`] : r.map(String))).join(",");
57
99
  }
58
100
  const printRepeat = (r) => (r === null ? "" : r === "open" ? " x ..." : ` x${r}`);
59
101
  function printKey(k) {
@@ -95,7 +137,7 @@ export function printLine(l, beats = []) {
95
137
  case "directive":
96
138
  return printDirectives(l.set);
97
139
  case "bars":
98
- return `${l.opens ? "|:" : "|"} ${l.cells.map((c, i) => printCell(c, beats[i])).join(" | ")} ${l.closes ? ":|" : "|"}${printRepeat(l.repeat)}`;
140
+ return `${l.opens ? "|:" : l.ending ? `|${printPasses(l.ending)}` : "|"} ${l.cells.map((c, i) => printCell(c, beats[i])).join(" | ")} ${l.closes ? ":|" : "|"}${printRepeat(l.repeat)}`;
99
141
  default:
100
142
  return l.text;
101
143
  }
@@ -120,7 +162,7 @@ export function printParsed(text, parsed, edit = (l) => l) {
120
162
  for (const b of parsed.bars) {
121
163
  const l = byLine.get(b.line);
122
164
  const meters = firstPlay.get(b.line) ?? [];
123
- const cells = l?.kind === "bars" ? l.cells.filter((c) => c.kind !== "fermata").length : 0;
165
+ const cells = l?.kind === "bars" ? l.cells.filter(isBar).length : 0;
124
166
  if (meters.length < cells)
125
167
  firstPlay.set(b.line, [...meters, beatsOf(b.meter)]);
126
168
  }
@@ -129,7 +171,7 @@ export function printParsed(text, parsed, edit = (l) => l) {
129
171
  return [];
130
172
  const meters = firstPlay.get(l.line) ?? [];
131
173
  let next = 0;
132
- return l.cells.map((c) => (c.kind === "fermata" ? undefined : meters[next++]));
174
+ return l.cells.map((c) => (isBar(c) ? meters[next++] : undefined));
133
175
  };
134
176
  const out = [];
135
177
  let lastWasHeading = false;
@@ -0,0 +1,28 @@
1
+ import type { Line, Repeat } from "./types.js";
2
+ type Report = (line: number, message: string, token: string) => void;
3
+ export type Entry = {
4
+ line: Line;
5
+ repeat: Repeat;
6
+ };
7
+ /** One ending: the passes it plays on and its bar line. */
8
+ export type Ending = {
9
+ passes: number[];
10
+ entry: Entry;
11
+ };
12
+ /** A line, or a `|: … :|` repeat; one with endings plays `repeat` passes, each taking its ending. */
13
+ export type Item = ({
14
+ kind: "line";
15
+ } & Entry) | {
16
+ kind: "bracket";
17
+ line: number;
18
+ entries: Entry[];
19
+ repeat: Repeat;
20
+ endings: Ending[];
21
+ };
22
+ /**
23
+ * Pair `|:` and `:|` within one section's lines, with the endings that
24
+ * follow a repeat (grammar 5.1). Problems are reported, and what cannot
25
+ * pair plays once.
26
+ */
27
+ export declare function pairRepeats(lines: Line[], error: Report): Item[];
28
+ export {};