barmark 0.16.0 → 0.17.1

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,126 @@ Releases follow the process in [RELEASING.md](RELEASING.md).
9
9
 
10
10
  ## [Unreleased]
11
11
 
12
+ ## [0.17.1] - 2026-11-07
13
+
14
+ A parse is plain data that owns its objects, and the README says what it
15
+ holds and how to store charts.
16
+
17
+ ### Fixed
18
+
19
+ - **A chord's unaltered interval is `alter: 0`, never `-0`,** so a parse
20
+ written to JSON and read back is the same object, as the README now
21
+ promises.
22
+ - **Two parses share no objects.** A chord's intervals were the chord
23
+ vocabulary's own objects, shared by every parse in the process, so
24
+ changing one parse's intervals changed every later parse's. Each chord
25
+ now has its own.
26
+
27
+ ### Technical
28
+
29
+ - **The README documents the parse result**: what is written and what is
30
+ played, and why to store a chart's text and treat a stored parse as a
31
+ cache. A test holds every example chart's parse to a JSON round trip.
32
+
33
+ ## [0.17.0] - 2026-11-07
34
+
35
+ A grammar change: syllables on notes (4.3), lyric rows and verses in play
36
+ order (7.7), a part's bare line sharing a system with its named lines
37
+ (7.6, amended), `---` breaks and a leading `\` (1). Implements the
38
+ [grammar v0.1 draft](https://github.com/kevinpeckham/barmark/blob/main/docs/grammar-v0.1-draft.md).
39
+
40
+ **Changes what an existing chart means.** A line of only `---` (three or
41
+ more hyphens) is now a break that ends a system, not text. A part's bare
42
+ line followed directly by its named lines (`Pno | C |` then
43
+ `Pno.RH | … |`) is now one system, the bare line the part's first line;
44
+ it used to be two systems played one after the other (put `---` between
45
+ them for that). Also: a `lyrics:` or `lyrics N:` line followed by a bar
46
+ line is a lyric row, and a text line's leading `\` is no longer shown.
47
+
48
+ ### Added
49
+
50
+ - `---` (three or more hyphens alone) ends a system and means nothing else;
51
+ it parses as a `break` line and prints as `---` (grammar 1, 7.4).
52
+ - Syllables on notes (grammar 4.3): `{G4}:maz-` sings a syllable on a note
53
+ set, a trailing `-` continues the word, `:/` holds the syllable before
54
+ over a new note and `~` joins elided syllables (`{C4}:the~end`). A dotted
55
+ note takes its dot before the colon (`{C4}.:maz-`). The slot gains
56
+ `syllable` (the new `Syllable` type); the printer writes it back, and `%`
57
+ copies a bar's notes without their syllables. A syllable on a chord
58
+ name, a voicing, `/`, `--`, `N.C.` or `?`, an empty one, or `:/-` (a
59
+ hold can't begin or continue a word) is an error.
60
+ A syllable ends only at a space, `_`, `|`, `{` or a straight quote, so
61
+ curly quotes and brackets are characters of it (`{C4}:“Ho-`,
62
+ `{C4}:[x]`): they open no words and no one-bar meter.
63
+ - Lyric rows (grammar 7.7): `lyrics:` or `lyrics N:` (verse N) then a bar
64
+ line writes syllables on the beats, its bars divided as a chord row's
65
+ (`/` holds, `_` splits a slot, `--` is a breath). A row covers the bar
66
+ line or system just above it, or under a replay heading the replayed
67
+ section's lines in order, and must match its bar count. It parses as a
68
+ `lyrics` line (the new `LyricSlot` type) with `verse`, `cells` and
69
+ `covers`, the source lines of the bar lines it covers. The printer lines
70
+ a row up under its bars, the wider cell of each column setting its
71
+ width. A row with no bar line above it, a wrong bar count, an empty bar
72
+ or syllable, a quote or brace, or a verse number of 0 or past
73
+ `Number.MAX_SAFE_INTEGER` is an error.
74
+ - Verses in play order (grammar 7.7): each played bar gains `lyrics`, one
75
+ `PlayedLyrics` per verse it sings, each syllable with its onset `at` in
76
+ whole notes and `note` (true when a note of the singing line starts
77
+ there). Syllables on notes are verse 1 and `lyrics N:` verse N; outside a
78
+ repeat every verse is sung, and inside one verse N on pass N (a second
79
+ ending holds verse 2's words; a jump's pass back sings pass 1's). Bars
80
+ whose only verse is verse 1 sing it on every pass; a lone `lyrics N:`
81
+ row (N from 2) sings on pass N only, and the other passes warn. A
82
+ replay's rows replace its words. The first part with `instrument: voice`,
83
+ else the first with syllables, sings; its `DeclaredPart` gains `sings`,
84
+ the line its notes carry the syllables on. `lyrics 1:` or an unnumbered
85
+ row under notes with syllables, an unnumbered row among numbered ones and
86
+ a verse written twice over the same bars are errors; a row's syllable
87
+ where the singing line starts no note, and a `:/` with nothing sung
88
+ before it, warn. Another part's extract (`extractPart`, `printPart`)
89
+ leaves the singer's rows out.
90
+ Syllables on a part's notes are that part's, so a choir chart's bars
91
+ carry one `PlayedLyrics` per part and verse (verse order, then score
92
+ order), each part's `DeclaredPart.sings` set; lyric rows stay the
93
+ singer's, and only the singer's syllables clash with a row over them.
94
+ A numbered verse that no pass sings, a repeat's pass that sings
95
+ nothing where other passes sing, and syllables on notes that no pass
96
+ sings (verse 1 on a second ending), warn.
97
+ A row's `/` where the singing line starts a new note is a held syllable
98
+ there (`{ kind: "held" }`, `note: true`), as `:/` on the notes is: a
99
+ melisma the converters extend and the renderer draws.
100
+ A row starting with `/` holds on what its verse last sang, in play
101
+ order, unless the verse breathed since, so a verse holds a word across
102
+ a line break. Before its verse has sung anything the `/` sings nothing
103
+ and warns as a `:/` with nothing sung before it does (so the export
104
+ writes no `<extend/>` with nothing before it).
105
+
106
+ ### Changed
107
+
108
+ - `Line` gains the `break` and `lyrics` kinds, so an exhaustive `switch`
109
+ on `Line["kind"]` needs a case for each.
110
+ - A text line written with a leading `\` now holds its text without the
111
+ backslash, marked `escaped: true`; the printer writes the backslash back.
112
+ The escaped-pipes warning still applies to the rest of the line, and a
113
+ chart whose only text is escaped no longer warns that it has no bar lines.
114
+ - A `---` line between endings no longer ends the repeat (grammar 5.1);
115
+ like text and credit lines, it may sit between them, and so may a lyric
116
+ row under an ending.
117
+ - `lyrics:` followed by a bar line is now a lyric row, not text with a
118
+ warning to write `lyricist:`; followed by anything else it still warns.
119
+ - A part's named lines written after its bare line now join it in a
120
+ system (grammar 7.6, amended): `Vox` then `Vox.Mel` play together, the
121
+ bare line as the part's first line (it holds the harmony; `Vox.Mel` holds
122
+ notes only). Such a part lists the bare line first in
123
+ `DeclaredPart.lines` as `""`, and its bars' `lines` give it the name
124
+ `""`; `extractPart(text, "Vox", "")` extracts it alone. A bare line
125
+ counts toward the four lines. Named lines written straight after their
126
+ part's bare line used to start a new system and now join it; put `---`
127
+ between them to keep them apart. A bare line after its part's named
128
+ lines still starts a new system. A bare line that is a fifth line
129
+ (an error) is dropped and none of the part's lines plays it: its four
130
+ named lines play, the first of them first.
131
+
12
132
  ## [0.16.0] - 2026-11-04
13
133
 
14
134
  A grammar change: part lines (7.6), sustain pedal marks (2.9), dotted
@@ -426,7 +546,9 @@ The first working release: the reference parser and printer for the
426
546
 
427
547
  - **A placeholder package that holds the `barmark` name** while the spec and parser are written.
428
548
 
429
- [Unreleased]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.16.0...HEAD
549
+ [Unreleased]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.17.1...HEAD
550
+ [0.17.1]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.17.0...barmark-v0.17.1
551
+ [0.17.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.16.0...barmark-v0.17.0
430
552
  [0.16.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.15.0...barmark-v0.16.0
431
553
  [0.15.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.14.1...barmark-v0.15.0
432
554
  [0.14.1]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.14.0...barmark-v0.14.1
package/README.md CHANGED
@@ -123,6 +123,32 @@ pedalStates(chart.bars); // whether the pedal is down after each slot
123
123
  `chart.part` still gives the one part of a single-part chart, and is
124
124
  deprecated in favour of `parts`.
125
125
 
126
+ ### Voice and lyrics
127
+
128
+ ```
129
+ part: Vox = Voice, instrument: voice
130
+ key: G, time: 3/4
131
+
132
+ Vox | [1/4] N.C. | G | G / G7 |
133
+ Vox.Mel | [1/4] {D4}:A- | {G4}:maz- / {B4}:ing_{G4}:/ | {B4}:grace / {A4}:how |
134
+ lyrics 2: | 'Twas | grace / that | taught / my |
135
+ ```
136
+
137
+ A lead sheet puts the chords on the voice part's bare line and its melody
138
+ on a second line, `Vox.Mel` (grammar 7.6). A syllable follows a note
139
+ after a colon (`{G4}:maz-`; a trailing `-` continues the word, `~` joins
140
+ elided syllables, `:/` holds the syllable over a new note). A **lyric
141
+ row** (`lyrics:`, or `lyrics N:` for verse N; grammar 7.7) writes later
142
+ verses under a system, one cell per bar. `---` on a line of its own
143
+ separates blocks, and a text line that starts with `\` is text.
144
+
145
+ ```ts
146
+ chart.bars[0].lyrics; // a PlayedLyrics per verse the bar sings: { verse, part?, syllables }
147
+ chart.parts[0].sings; // the name of the line whose notes carry the words ("Mel" here; "" for a bare line)
148
+ ```
149
+
150
+ Verses come out in play order: inside a repeat, verse N is pass N.
151
+
126
152
  - **`parseChart`** never throws. A line with an error is left out of the
127
153
  play order and reported, and the rest of the chart still reads.
128
154
  - **`printChart`** changes spelling and layout only: lines with errors and
@@ -141,6 +167,53 @@ deprecated in favour of `parts`.
141
167
  convert both ways. Every label in the McGill Billboard and Isophonics
142
168
  Beatles datasets converts to barmark with exactly the same notes.
143
169
 
170
+ ### The parse result, and storing charts
171
+
172
+ `parseChart` returns plain data: no classes, Maps or functions, so
173
+ `JSON.stringify` and `JSON.parse` give an equal object back. Inside one
174
+ parse, objects are shared (a bar in `bars` is the same object as in
175
+ `events`, and a `%` bar shares its slots), so treat a parse as read-only;
176
+ `structuredClone(chart)` gives a copy to change. Two parses never share
177
+ an object. It has two kinds of field:
178
+
179
+ - **The chart as written:** `title`, `parts`, `credits` and `lines`, one
180
+ entry per source line in order (the title, a bar line, a heading, a
181
+ directive, a `part:` line, a credit, a lyric row, text, a break, or an
182
+ invalid bar line kept as written), each with its line number.
183
+ - **The chart as played**, worked out from the written lines:
184
+ - `events` is play order with fermatas and an open repeat kept as
185
+ events.
186
+ - `bars` is the same flattened to one `PlayedBar` per measure played,
187
+ repeats, endings, jumps and replays spelled out. A bar's `index` counts
188
+ in play order; `written` is the number a band reads on the page, the
189
+ same on every pass. Each bar carries its slots, section, key, meter,
190
+ tempo, feel and, when sung, each verse's syllables (`lyrics`).
191
+ - `sections` is each section as played, with its first and last bar and
192
+ `form` (which distinct section it is; replays share their section's
193
+ number).
194
+ - **`diagnostics`:** every error and warning, with its line. `parseChart`
195
+ never throws; a chart with errors still parses what it can.
196
+
197
+ The parse is tens to hundreds of times the size of the text, a few
198
+ kilobytes for each bar played: a 700-byte song whose repeats and replays
199
+ play out parses to about 170 KB of JSON. Its shape follows this
200
+ package's minor versions: 0.17.0, for example, added the `break` and
201
+ `lyrics` line kinds. So:
202
+
203
+ - **Store the text.** It is the stable format: the grammar defines it,
204
+ `printChart` gives it one canonical spelling, and re-parsing an old
205
+ chart with a newer barmark gives the current shape.
206
+ - **Treat a stored parse as a cache**, tagged with the barmark version
207
+ that made it, and parse again when the version changes.
208
+ - **To check a chart before storing it**, parse it and look for
209
+ diagnostics with `severity: "error"`; store `printChart(text)` to keep
210
+ one spelling of each chart.
211
+ - **Times in a recording** belong beside the chart, not in it: key them
212
+ by `PlayedBar.index`, which names the same bar however the chart is
213
+ reformatted or its repeats are spelled (`|: :|` or `x2`), until the
214
+ music itself changes. An open repeat (`x ...`) plays its bars once in
215
+ `bars`, so its later passes have no index of their own.
216
+
144
217
  ## Develop
145
218
 
146
219
  ```
@@ -3,6 +3,7 @@ import { parseNoteSet } from "../chords/noteSet.js";
3
3
  import { parseChord } from "../chords/parse.js";
4
4
  import { isDirectionWord, readDirection } from "./direction.js";
5
5
  import { parseMeter } from "./directives.js";
6
+ import { readSyllable, splitSyllable } from "./syllable.js";
6
7
  const FERMATA = new Set(["...", "…"]);
7
8
  /** Whether a cell is a bar: `...`, a direction and a rehearsal mark mark a place between bars. */
8
9
  export const isBar = (c) => c.kind === "slots" || c.kind === "simile";
@@ -179,6 +180,32 @@ const isDirectionCell = (p) => {
179
180
  const d = readDirection(p);
180
181
  return !!d && "direction" in d;
181
182
  };
183
+ /** Where a syllable ends (grammar 4.3): a space, `_`, `|`, `{` or a straight quote. */
184
+ const SYLLABLE_END = /[\s_|{"]/;
185
+ /**
186
+ * Which of a cell's characters belong to a syllable: those after the colon
187
+ * that follows a note set's brace (and a rhythm's dot), up to its end. In a
188
+ * syllable a curly quote or a `[` is a character like any other.
189
+ */
190
+ function inSyllables(chars) {
191
+ const out = [];
192
+ let sung = false;
193
+ chars.forEach((ch, i) => {
194
+ if (sung && SYLLABLE_END.test(ch))
195
+ sung = false;
196
+ out.push(sung);
197
+ const before = chars[i - 1] === "." ? chars[i - 2] : chars[i - 1];
198
+ if (!sung && ch === ":" && before === "}")
199
+ sung = true;
200
+ });
201
+ return out;
202
+ }
203
+ /** A cell's text with its syllables blanked, to look for what only the rest of it holds. */
204
+ const outsideSyllables = (cell) => {
205
+ const chars = [...cell];
206
+ const sung = inSyllables(chars);
207
+ return chars.map((ch, i) => (sung[i] ? " " : ch)).join("");
208
+ };
182
209
  /**
183
210
  * Quoted words out of a cell (grammar 2.6): the cell with each one blanked,
184
211
  * and where each goes, before the slot it precedes.
@@ -187,8 +214,9 @@ function readWords(cell) {
187
214
  const words = [];
188
215
  let bare = "";
189
216
  let open = null;
217
+ const sung = inSyllables([...cell]);
190
218
  for (const [i, ch] of [...cell].entries()) {
191
- if (!QUOTES.has(ch)) {
219
+ if (!QUOTES.has(ch) || (sung[i] && open === null)) {
192
220
  if (open === null)
193
221
  bare += ch;
194
222
  continue;
@@ -303,6 +331,30 @@ function marksProblem(marks, inGroup, token) {
303
331
  const broken = MARK_RULES.find(([breaks]) => breaks(marks, inGroup));
304
332
  return broken ? { problem: broken[1], token } : null;
305
333
  }
334
+ const NOT_A_NOTE_SET = "a syllable follows a note set, like {G4}:la";
335
+ /** The slot with this syllable sung on it, or why it can't be (grammar 4.3). */
336
+ function sungOn(slot, written) {
337
+ if (slot.kind === "chord" && slot.voicing)
338
+ return {
339
+ problem: `a syllable goes on a note set, not a voicing; write the notes alone (${slot.voicing.canonical}:${written})`,
340
+ };
341
+ if (slot.kind !== "chord" || slot.chord.kind !== "notes")
342
+ return { problem: NOT_A_NOTE_SET };
343
+ if (written.includes("{"))
344
+ return { problem: "a syllable ends at {; put a space before the next note" };
345
+ const syllable = readSyllable(written);
346
+ if (syllable)
347
+ return { ...slot, syllable };
348
+ return { problem: unreadSyllable(written) };
349
+ }
350
+ /** Why a syllable token reads as no syllable. */
351
+ function unreadSyllable(written) {
352
+ if (written === "/-")
353
+ return "a hold can't begin or continue a word; write :/ alone";
354
+ return written.includes("~")
355
+ ? "~ joins two syllables; write one on each side"
356
+ : "an empty syllable; write one after the colon, or leave the note unsung";
357
+ }
306
358
  /** Whether a voicing's note is one of the chord's, by pitch class. */
307
359
  const inChord = (note, chord) => {
308
360
  const pc = (n) => (noteSemitone(n.replace(/\d|!/g, "")) + 12) % 12;
@@ -481,17 +533,34 @@ export function parseBarLine(text, line) {
481
533
  const s = markedSlot(m.slice(0, -1), true);
482
534
  return s && { ...s, dotted: true };
483
535
  };
536
+ /** A slot read by `read`, with the syllable written after it, if any (grammar 4.3). */
537
+ const withSyllable = ({ note, syllable }, read) => {
538
+ const written = `${note}:${syllable}`;
539
+ if (syllable !== null && !note)
540
+ return error(NOT_A_NOTE_SET, written);
541
+ const slot = read(note);
542
+ if (syllable === null || !slot)
543
+ return slot;
544
+ const sung = sungOn(slot, syllable);
545
+ return "problem" in sung ? error(sung.problem, written) : sung;
546
+ };
484
547
  /** One slot token: a simple slot, or a `_` group of them. */
485
548
  const slotOf = (token) => {
486
- const members = groupMembers(token);
487
- if (members.length === 1)
488
- return isDotted(token) ? error(DOT_PLACE, token) : markedSlot(token, false);
489
- const dots = members.filter(isDotted).length;
490
- if (dots && (members.length > 2 || dots > 1))
549
+ const members = groupMembers(token).map(splitSyllable);
550
+ const dots = members.filter((m) => isDotted(m.note)).length;
551
+ if (dots && (members.length !== 2 || dots > 1))
491
552
  return error(DOT_PLACE, token);
553
+ const [only] = members;
554
+ if (only && members.length === 1)
555
+ return withSyllable(only, (n) => markedSlot(n, false));
556
+ return groupOf(members, token);
557
+ };
558
+ const groupOf = (members, token) => {
492
559
  const out = [];
493
560
  for (const m of members) {
494
- const s = m ? memberOf(m) : error("an empty member in a group", token);
561
+ const s = m.note || m.syllable !== null
562
+ ? withSyllable(m, memberOf)
563
+ : error("an empty member in a group", token);
495
564
  if (s)
496
565
  out.push(s);
497
566
  }
@@ -508,7 +577,7 @@ export function parseBarLine(text, line) {
508
577
  if ("problem" in read)
509
578
  return report(read);
510
579
  const { bare, words } = read;
511
- if (bare.includes("["))
580
+ if (outsideSyllables(bare).includes("["))
512
581
  return error("a [n/d] meter must start its cell", rest);
513
582
  const alone = standalone(bare, meter, words);
514
583
  if (alone)
@@ -3,7 +3,7 @@ import type { ChartDiagnostic, CreditRole, Credits, Line } from "./types.js";
3
3
  export declare const CREDIT_ROLES: readonly CreditRole[];
4
4
  /** A credit line, or null when the line isn't one (grammar 7.5). */
5
5
  export declare function readCredit(text: string, line: number, diagnostics: ChartDiagnostic[]): Line | null;
6
- /** A text line that reads like a credit under another name: `author: X`. */
6
+ /** A text line that reads like a credit under another name: `author: X` (not a lyric row, 7.7). */
7
7
  export declare function nearCredit(text: string, line: number): ChartDiagnostic | null;
8
8
  /** Every credit line's text, by role, in written order. */
9
9
  export declare function creditsOf(lines: Line[]): Credits;
@@ -1,4 +1,5 @@
1
1
  import { DIRECTIVE_AFTER } from "./directives.js";
2
+ import { LYRIC_ROW } from "./lyricRows.js";
2
3
  /** The credit roles, in the order MusicXML writes them (grammar 7.5). */
3
4
  export const CREDIT_ROLES = [
4
5
  "composer",
@@ -38,8 +39,11 @@ export function readCredit(text, line, diagnostics) {
38
39
  });
39
40
  return { kind: "credit", line, role, text: value };
40
41
  }
41
- /** A text line that reads like a credit under another name: `author: X`. */
42
+ /** A text line that reads like a credit under another name: `author: X` (not a lyric row, 7.7). */
42
43
  export function nearCredit(text, line) {
44
+ // `lyrics:` then a bar line is a lyric row (7.7); escaped, it is text, and no near miss.
45
+ if (LYRIC_ROW.test(text))
46
+ return null;
43
47
  const m = /^([^\s:]+)\s*:\s*(.*)$/.exec(text);
44
48
  const role = m?.[1] ? NEAR_CREDITS[m[1].toLowerCase()] : undefined;
45
49
  if (!m || !role)
@@ -3,6 +3,7 @@ import { misplacedRepeat, parseBarLine, readRepeat, repeatTail } from "./barLine
3
3
  import { creditsOf, nearCredit, readCredit } from "./credits.js";
4
4
  import { parseDirectiveLine } from "./directives.js";
5
5
  import { checkLines } from "./lines.js";
6
+ import { attachLyrics, readLyricRow } from "./lyricRows.js";
6
7
  import { readPart } from "./partLine.js";
7
8
  import { groupSystems } from "./systems.js";
8
9
  const NEAR_DIRECTIVES = {
@@ -108,6 +109,8 @@ function splitLabel(t) {
108
109
  }
109
110
  const LINE_NAME = /^[A-Za-z0-9]+$/;
110
111
  /** A label and the bar line after it: `Gtr | G |` (grammar 7.4). */
112
+ /** Three or more hyphens alone: `---` ends a system (grammar 1, 7.4). */
113
+ const BREAK = /^-{3,}$/;
111
114
  const LABELLED = /^([^\s|]+)(\s*)(\|.*)$/;
112
115
  const readsCleanly = (barLine) => {
113
116
  const read = parseBarLine(barLine, 0);
@@ -188,7 +191,7 @@ function escapedBarLine(text) {
188
191
  function noBarLines(lines) {
189
192
  if (lines.some((l) => l.kind === "bars" || l.kind === "invalid"))
190
193
  return null;
191
- const first = lines.find((l) => l.kind === "text");
194
+ const first = lines.find((l) => l.kind === "text" && !l.escaped);
192
195
  if (first?.kind !== "text")
193
196
  return null;
194
197
  return {
@@ -285,9 +288,32 @@ export function readDocument(text) {
285
288
  const read = barLine(rest, line);
286
289
  return read.kind === "bars" || read.kind === "invalid" ? { ...read, ...owner } : read;
287
290
  };
291
+ /** A leading `\` makes the rest text, whatever it looks like (grammar 1). */
292
+ const escapedLine = (t, line) => {
293
+ const text = t.slice(1);
294
+ const old = oldFormat(text, line);
295
+ if (old)
296
+ diagnostics.push(old);
297
+ return { kind: "text", line, text, escaped: true };
298
+ };
299
+ /** `lyrics:` or `lyrics N:` then a bar line (grammar 7.7); one with an error stays text. */
300
+ const lyricRow = (t, line) => {
301
+ const read = readLyricRow(t, line);
302
+ diagnostics.push(...read.diagnostics);
303
+ if (read.row || read.diagnostics.length)
304
+ return read.row ?? { kind: "text", line, text: t };
305
+ return null;
306
+ };
288
307
  const classify = (t, line) => {
308
+ if (BREAK.test(t))
309
+ return { kind: "break", line };
310
+ if (t.startsWith("\\"))
311
+ return escapedLine(t, line);
289
312
  if (t.startsWith("|"))
290
313
  return barLine(t, line);
314
+ const row = lyricRow(t, line);
315
+ if (row)
316
+ return row;
291
317
  const labelled = labelledLine(t, line);
292
318
  if (labelled)
293
319
  return labelled;
@@ -310,14 +336,15 @@ export function readDocument(text) {
310
336
  diagnostics.push(empty);
311
337
  const read = checkParts(lines, diagnostics);
312
338
  const grouped = groupParts(lines, read);
313
- diagnostics.push(...grouped.diagnostics);
339
+ const lyrics = attachLyrics(grouped.lines);
340
+ diagnostics.push(...grouped.diagnostics, ...lyrics.diagnostics);
314
341
  const { parts } = grouped;
315
342
  return {
316
343
  title,
317
344
  part: parts.length === 1 ? (parts[0] ?? null) : null,
318
345
  parts,
319
346
  credits: creditsOf(lines),
320
- lines: grouped.lines,
347
+ lines: lyrics.lines,
321
348
  diagnostics,
322
349
  };
323
350
  }
@@ -1,4 +1,18 @@
1
1
  import type { ChartDiagnostic, ChartEvent, Line, PlayedBar, SectionOccurrence } from "./types.js";
2
+ /**
3
+ * Where a played bar comes from, for its words (grammar 7.7): its bar
4
+ * line, its place among that line's bars (from 0), the pass of the repeat
5
+ * it plays in (null outside one, and in an open repeat, whose passes are
6
+ * unknown), and the line of the replay heading it plays under, if any.
7
+ */
8
+ export type BarSource = {
9
+ line: number;
10
+ bar: number;
11
+ pass: number | null;
12
+ replay: number | null;
13
+ };
14
+ /** The words a played bar sings, given where it comes from; undefined when none. */
15
+ export type Sing = (bar: PlayedBar, from: BarSource) => PlayedBar["lyrics"];
2
16
  /** Nested repeats multiply; expansion stops here rather than run away. */
3
17
  export declare const MAX_EXPANDED_BARS = 10000;
4
18
  /** Every played bar in order, with an open repeat's pass included once. */
@@ -13,7 +27,9 @@ export declare function flattenBars(events: ChartEvent[]): PlayedBar[];
13
27
  */
14
28
  export declare function expand(lines: Line[], label?: string, share?: number,
15
29
  /** False for one line of a part (grammar 7.6): the pedal is the part's, warned of once its lines are folded. */
16
- pedal?: boolean): {
30
+ pedal?: boolean,
31
+ /** The words each bar sings, for the line that sings them (grammar 7.7). */
32
+ sing?: Sing): {
17
33
  events: ChartEvent[];
18
34
  sections: SectionOccurrence[];
19
35
  diagnostics: ChartDiagnostic[];
@@ -2,9 +2,17 @@ import { planJump } from "./direction.js";
2
2
  import { beatsOf } from "./directives.js";
3
3
  import { pedalWarnings } from "./pedal.js";
4
4
  import { pairRepeats } from "./repeats.js";
5
- import { memberShares } from "./shares.js";
5
+ import { slotTimes } from "./shares.js";
6
6
  /** Nested repeats multiply; expansion stops here rather than run away. */
7
7
  export const MAX_EXPANDED_BARS = 10_000;
8
+ /** A slot without its syllable: `%` copies a bar's notes, not its words (grammar 4.3). */
9
+ const unsungSimple = (s) => {
10
+ if (s.kind !== "chord" || !s.syllable)
11
+ return s;
12
+ const { syllable: _, ...rest } = s;
13
+ return rest;
14
+ };
15
+ const unsung = (s) => s.kind === "group" ? { ...s, members: s.members.map(unsungSimple) } : unsungSimple(s);
8
16
  /**
9
17
  * How each mark moves play along. A mark the jump does not use is an error
10
18
  * that drops the jump, so with a jump planned every mark here applies.
@@ -29,16 +37,6 @@ function uneven(slots, meter, line) {
29
37
  }
30
38
  const PUSH_MARKS = { eighth: "<", sixteenth: "<<" };
31
39
  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
- ? memberShares(s.members).map((share, i) => ({
37
- slot: s.members[i],
38
- length: each * share,
39
- }))
40
- : [{ slot: s, length: each }]);
41
- }
42
40
  /** Why a push can't take its time from a slot this long; null when it can. */
43
41
  function pushProblem(push, before) {
44
42
  if (before === null)
@@ -88,7 +86,9 @@ function removeLastBar(events) {
88
86
  */
89
87
  export function expand(lines, label, share = 1,
90
88
  /** False for one line of a part (grammar 7.6): the pedal is the part's, warned of once its lines are folded. */
91
- pedal = true) {
89
+ pedal = true,
90
+ /** The words each bar sings, for the line that sings them (grammar 7.7). */
91
+ sing) {
92
92
  const diagnostics = [];
93
93
  const maxBars = Math.max(1, Math.floor(MAX_EXPANDED_BARS / share));
94
94
  // Repeats of bodies that play no bars (fermatas only) are bounded too.
@@ -139,8 +139,8 @@ pedal = true) {
139
139
  else if (previous.tacet)
140
140
  tacetBefore(line, "% has nothing to copy");
141
141
  const meter = previous?.meter ?? null;
142
- const slots = previous?.slots ?? [{ kind: "hold" }];
143
- return marked({ kind: "bar", meter, slots, own: false, written: ++written }, c.words);
142
+ const slots = previous?.slots.map(unsung) ?? [{ kind: "hold" }];
143
+ return marked({ kind: "bar", meter, slots, own: false, written: ++written, bar: 0 }, c.words);
144
144
  };
145
145
  /** A bar that opens with `/` holds what was sounding before it. */
146
146
  const checkHold = (c, line) => {
@@ -162,6 +162,7 @@ pedal = true) {
162
162
  slots: c.slots,
163
163
  own: true,
164
164
  written: ++written,
165
+ bar: 0,
165
166
  ...(c.tacet && { tacet: c.tacet }),
166
167
  };
167
168
  return marked(bar, c.words);
@@ -180,7 +181,11 @@ pedal = true) {
180
181
  written += l.written;
181
182
  if (l.kind !== "bars")
182
183
  continue;
183
- resolved.set(l, l.cells.map((c) => resolveCell(c, l.line)).filter((p) => p !== null));
184
+ let bar = 0;
185
+ resolved.set(l, l.cells
186
+ .map((c) => resolveCell(c, l.line))
187
+ .filter((p) => p !== null)
188
+ .map((p) => (p.kind === "bar" ? { ...p, bar: bar++ } : p)));
184
189
  }
185
190
  const unused = pending.mark;
186
191
  if (unused)
@@ -245,6 +250,8 @@ pedal = true) {
245
250
  error(line, `expansion stopped at ${maxBars} bars`, "x");
246
251
  };
247
252
  let sectionName = null;
253
+ /** The pass of the repeat being played, and the replay heading being played, for the words (grammar 7.7). */
254
+ const where = { pass: null, replay: null };
248
255
  let phase = "main";
249
256
  const stopped = () => capped || phase === "jumped" || phase === "done";
250
257
  const jumped = () => phase === "jumped";
@@ -281,12 +288,18 @@ pedal = true) {
281
288
  ...(p.tacet && { tacet: p.tacet }),
282
289
  };
283
290
  };
291
+ /** The bar with the words it sings here, if any (grammar 7.7). */
292
+ const sung = (bar, p, line) => {
293
+ const lyrics = sing?.(bar, { line, bar: p.bar, ...where });
294
+ return lyrics ? { ...bar, lyrics } : bar;
295
+ };
284
296
  /** How long the slot played just before is, in whole notes; null after a fermata or at the start. */
285
297
  const before = { length: null };
286
298
  const pushReported = new Set();
287
299
  /** Each push takes its time from the slot played just before it (grammar 2.8). */
288
300
  const checkPushes = (bar) => {
289
- for (const { slot, length } of timed(bar)) {
301
+ const timed = slotTimes(bar.slots, bar.meter);
302
+ for (const { slot, length } of timed) {
290
303
  const problem = slot.push && pushProblem(slot.push, before.length);
291
304
  const key = `${bar.line}\u0000${problem}`;
292
305
  if (problem && !pushReported.has(key)) {
@@ -314,7 +327,7 @@ pedal = true) {
314
327
  count++;
315
328
  const bar = barOf(p, line);
316
329
  checkPushes(bar);
317
- out.push({ kind: "bar", bar });
330
+ out.push({ kind: "bar", bar: sung(bar, p, line) });
318
331
  };
319
332
  /** Play `body` `repeat` times into `out`; an open repeat plays one pass inside an open event. */
320
333
  const times = (repeat, line, out, body) => {
@@ -334,12 +347,19 @@ pedal = true) {
334
347
  return;
335
348
  }
336
349
  // After the jump every repeat plays once.
337
- const passes = phase === "main" ? (repeat ?? 1) : 1;
338
- for (let i = 0; i < passes && !stopped(); i++) {
350
+ passes(phase === "main" ? (repeat ?? 1) : 1, repeat !== null, line, () => body(out));
351
+ };
352
+ /** Play `n` passes; a repeat's are numbered for the words (grammar 7.7), a plain line's are not. */
353
+ const passes = (n, counted, line, play) => {
354
+ const outer = where.pass;
355
+ for (let i = 0; i < n && !stopped(); i++) {
339
356
  if (++work > maxWork)
340
357
  return stop(line);
341
- body(out);
358
+ if (counted)
359
+ where.pass = i + 1;
360
+ play();
342
361
  }
362
+ where.pass = outer;
343
363
  };
344
364
  const playLine = ({ line: l, repeat }, out) => {
345
365
  if (stopped())
@@ -370,15 +390,19 @@ pedal = true) {
370
390
  const playEndings = (it, out) => {
371
391
  const highest = typeof it.repeat === "number" ? it.repeat : 1;
372
392
  const first = phase === "main" ? 1 : highest;
393
+ const outer = where.pass;
373
394
  for (let pass = first; pass <= highest && !stopped(); pass++) {
374
395
  if (++work > maxWork)
375
396
  return stop(it.line);
397
+ // The return after a jump is no new pass: it plays pass 1's words (grammar 7.7).
398
+ where.pass = phase === "main" ? pass : 1;
376
399
  for (const e of it.entries)
377
400
  playLine(e, out);
378
401
  const ending = it.endings.find((x) => x.passes.includes(pass));
379
402
  if (ending)
380
403
  playLine(ending.entry, out);
381
404
  }
405
+ where.pass = outer;
382
406
  };
383
407
  const events = [];
384
408
  const occurrences = [];
@@ -410,7 +434,9 @@ pedal = true) {
410
434
  error(h.line, unmatchedReplay(h, sections), h.name);
411
435
  return null;
412
436
  }
437
+ where.replay = h.line;
413
438
  times(h.repeat, h.line, out, (into) => playItems(itemsOf.get(source) ?? [], into));
439
+ where.replay = null;
414
440
  const elided = h.elided && removeLastBar(out);
415
441
  // A replay heading stands for its bars: its own lines (directives) come after them.
416
442
  playItems(itemsOf.get(s) ?? [], out);