barmark 0.14.1 → 0.16.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.
@@ -0,0 +1,48 @@
1
+ export const CLEF_NAMES = ["treble", "bass", "treble 8vb", "alto"];
2
+ const SOUNDING = { diatonic: 0, chromatic: 0 };
3
+ const OCTAVE_UP = { diatonic: 7, chromatic: 12 };
4
+ const row = (name, clef, staves, program, written = SOUNDING) => ({ name, clef, staves, written, program });
5
+ export const INSTRUMENTS = [
6
+ row("piano", "treble", 2, 1),
7
+ row("electric piano", "treble", 2, 5),
8
+ row("organ", "treble", 2, 17),
9
+ row("synth", "treble", 2, 81),
10
+ // A guitar's treble 8vb clef carries its octave: written where it sounds.
11
+ row("acoustic guitar", "treble 8vb", 1, 26),
12
+ row("electric guitar", "treble 8vb", 1, 28),
13
+ row("electric bass", "bass", 1, 34, OCTAVE_UP),
14
+ row("double bass", "bass", 1, 33, OCTAVE_UP),
15
+ row("trumpet in Bb", "treble", 1, 57, { diatonic: 1, chromatic: 2 }),
16
+ row("alto sax", "treble", 1, 66, { diatonic: 5, chromatic: 9 }),
17
+ row("tenor sax", "treble", 1, 67, { diatonic: 8, chromatic: 14 }),
18
+ row("trombone", "bass", 1, 58),
19
+ row("flute", "treble", 1, 74),
20
+ row("violin", "treble", 1, 41),
21
+ row("cello", "bass", 1, 43),
22
+ row("voice", "treble", 1, 53),
23
+ ];
24
+ const key = (s) => s.toLowerCase().replace(/\s+/g, " ").trim();
25
+ /** The listed instrument with this name, in any case; null when there is none. */
26
+ export function instrumentInfo(name) {
27
+ return INSTRUMENTS.find((i) => key(i.name) === key(name)) ?? null;
28
+ }
29
+ /** Levenshtein distance, for near names. */
30
+ function distance(a, b) {
31
+ let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
32
+ for (let i = 1; i <= a.length; i++) {
33
+ const next = [i];
34
+ for (let j = 1; j <= b.length; j++)
35
+ next[j] = Math.min((prev[j] ?? 0) + 1, (next[j - 1] ?? 0) + 1, (prev[j - 1] ?? 0) + (a[i - 1] === b[j - 1] ? 0 : 1));
36
+ prev = next;
37
+ }
38
+ return prev[b.length] ?? 0;
39
+ }
40
+ /** The listed names an unknown one is near: those holding all its words, or else within two edits. */
41
+ export function nearInstruments(name) {
42
+ const words = key(name).split(" ");
43
+ const holding = INSTRUMENTS.filter((i) => words.every((w) => key(i.name).split(" ").includes(w)));
44
+ const near = holding.length
45
+ ? holding
46
+ : INSTRUMENTS.filter((i) => distance(key(i.name), key(name)) <= 2);
47
+ return near.map((i) => i.name);
48
+ }
@@ -0,0 +1,14 @@
1
+ import type { ChartDiagnostic, DeclaredPart, Line, Part } from "./types.js";
2
+ /** At most this many lines per part (grammar 7.6). */
3
+ export declare const MAX_LINES = 4;
4
+ /**
5
+ * Check a chart's part lines (grammar 7.6), after systems are numbered:
6
+ * names, the four-line limit, score order, and that only a part's first
7
+ * line in a system, in score order, holds harmony or pedal marks. A line that breaks a rule is an
8
+ * error and is marked `dropped`. Never throws.
9
+ */
10
+ export declare function checkLines(lines: Line[], parts: Part[]): {
11
+ lines: Line[];
12
+ parts: DeclaredPart[];
13
+ diagnostics: ChartDiagnostic[];
14
+ };
@@ -0,0 +1,98 @@
1
+ /** At most this many lines per part (grammar 7.6). */
2
+ export const MAX_LINES = 4;
3
+ const isLabelled = (l) => (l.kind === "bars" || l.kind === "invalid") && l.part !== undefined;
4
+ const members = (s) => (s.kind === "group" ? s.members : [s]);
5
+ const slotsOf = (l) => l.cells.flatMap((c) => (c.kind === "slots" ? c.slots.flatMap(members) : []));
6
+ /** Why a line that is not its part's first in a system can't be what it is, or null (grammar 7.6). */
7
+ function notesOnlyProblem(l) {
8
+ const slots = slotsOf(l);
9
+ const harmony = slots.some((s) => s.kind === "nc" ||
10
+ s.kind === "unknown" ||
11
+ (s.kind === "chord" && (s.chord.kind !== "notes" || s.voicing !== undefined)));
12
+ if (harmony)
13
+ return "chord symbols go on the part's first line; write a note set here, or a voicing on the first line";
14
+ return slots.some((s) => s.kind === "chord" && s.pedal)
15
+ ? "a pedal mark goes on the part's first line"
16
+ : null;
17
+ }
18
+ /** Each part's line names in first-appearance order, each line renamed to its first spelling; a fifth is an error. */
19
+ function nameLines(lines, report) {
20
+ const names = new Map();
21
+ const out = lines.map((l) => {
22
+ if (!isLabelled(l) || l.lineName === undefined)
23
+ return l;
24
+ const own = names.get(l.part ?? "") ?? [];
25
+ const known = own.find((n) => n.toLowerCase() === l.lineName?.toLowerCase());
26
+ if (known)
27
+ return { ...l, lineName: known };
28
+ if (own.length >= MAX_LINES)
29
+ return report(l, "a part has at most four lines");
30
+ names.set(l.part ?? "", [...own, l.lineName]);
31
+ return l;
32
+ });
33
+ return { lines: out, names };
34
+ }
35
+ /** A system's lines by part, in written order. */
36
+ function byPart(system) {
37
+ const out = new Map();
38
+ for (const l of system)
39
+ out.set(l.part ?? "", [...(out.get(l.part ?? "") ?? []), l]);
40
+ return out;
41
+ }
42
+ /**
43
+ * Each part's score order (grammar 7.6): its lines as the first system
44
+ * writing two or more of them writes them, then any others in the order
45
+ * they first appear.
46
+ */
47
+ function scoreOrder(names, systems) {
48
+ const out = new Map();
49
+ for (const [part, all] of names) {
50
+ const full = systems
51
+ .map((s) => (byPart(s).get(part) ?? []).flatMap((l) => l.lineName ?? []))
52
+ .find((n) => n.length > 1);
53
+ const first = full ?? [];
54
+ out.set(part, [...first, ...all.filter((n) => !first.includes(n))]);
55
+ }
56
+ return out;
57
+ }
58
+ /** A system's lines of each part, after the first in score order, hold notes only. */
59
+ function checkSystem(system, order, report) {
60
+ for (const [part, written] of byPart(system)) {
61
+ const rank = (l) => l.lineName === undefined ? -1 : (order.get(part) ?? []).indexOf(l.lineName);
62
+ const own = [...written].sort((a, b) => rank(a) - rank(b));
63
+ for (const l of own.slice(1)) {
64
+ const problem = l.kind === "bars" ? notesOnlyProblem(l) : null;
65
+ if (problem)
66
+ report(l, problem);
67
+ }
68
+ }
69
+ }
70
+ /**
71
+ * Check a chart's part lines (grammar 7.6), after systems are numbered:
72
+ * names, the four-line limit, score order, and that only a part's first
73
+ * line in a system, in score order, holds harmony or pedal marks. A line that breaks a rule is an
74
+ * error and is marked `dropped`. Never throws.
75
+ */
76
+ export function checkLines(lines, parts) {
77
+ const diagnostics = [];
78
+ const failed = new Set();
79
+ const report = (l, message) => {
80
+ diagnostics.push({ line: l.line, severity: "error", message, token: l.part ?? "" });
81
+ failed.add(l.line);
82
+ return l;
83
+ };
84
+ const named = nameLines(lines, report);
85
+ const systems = new Map();
86
+ for (const l of named.lines)
87
+ if (isLabelled(l) && l.system !== undefined && !failed.has(l.line))
88
+ systems.set(l.system, [...(systems.get(l.system) ?? []), l]);
89
+ const order = scoreOrder(named.names, [...systems.values()]);
90
+ for (const system of systems.values())
91
+ checkSystem(system, order, report);
92
+ const out = named.lines.map((l) => l.kind === "bars" && failed.has(l.line) ? { ...l, dropped: true } : l);
93
+ const declared = parts.map((p) => {
94
+ const own = order.get(p.label ?? "");
95
+ return own ? { ...p, lines: own } : p;
96
+ });
97
+ return { lines: out, parts: declared, diagnostics };
98
+ }
@@ -9,7 +9,10 @@ export declare function zipEvents(each: ChartEvent[][], report: (d: ChartDiagnos
9
9
  export declare function parseChart(text: string): ChartParse;
10
10
  /**
11
11
  * One part of a chart as a single-part chart (grammar 7.4): the tutti bars,
12
- * its own bars, and `N.C.` marked `tacet` where it rests. Null when the
13
- * chart declares no part with that label. Never throws.
12
+ * its own bars, and `N.C.` marked `tacet` where it rests. With `lineName`,
13
+ * one of the part's lines alone (grammar 7.6), as a converter writes each
14
+ * line: the part's first line also plays its bare and tutti lines, and a
15
+ * line rests where it isn't written. Null when the chart declares no part
16
+ * with that label, or the part no line of that name. Never throws.
14
17
  */
15
- export declare function extractPart(text: string, label: string): ChartParse | null;
18
+ export declare function extractPart(text: string, label: string, lineName?: string): ChartParse | null;
@@ -1,6 +1,7 @@
1
1
  import { readDocument } from "./document.js";
2
2
  import { expand, flattenBars } from "./expand.js";
3
- import { projectPart } from "./parts.js";
3
+ import { projectPart, projectPartLines } from "./parts.js";
4
+ import { pedalWarnings } from "./pedal.js";
4
5
  const RANK = { error: 0, warning: 1 };
5
6
  /** Sorted by line, errors before warnings. */
6
7
  const sortDiagnostics = (all) => all.sort((a, b) => a.line - b.line || RANK[a.severity] - RANK[b.severity]);
@@ -78,21 +79,85 @@ export function zipEvents(each, report) {
78
79
  return e;
79
80
  });
80
81
  }
81
- /** Several parts: each projected and played, then zipped into one timeline (grammar 7.4). */
82
- function playParts(lines, parts) {
83
- const played = parts.map((p) => expand(projectPart(lines, parts, p.label ?? ""), p.label, parts.length));
82
+ const streamsOf = (shown) => shown.flatMap((p, part) => p.lines?.length
83
+ ? p.lines.map((name) => ({ part, label: p.label ?? "", name }))
84
+ : [{ part, label: p.label ?? "", name: null }]);
85
+ /** A part's share of a bar from its streams' shares: its first playing line leads (grammar 7.6). */
86
+ function partOf(p, own) {
87
+ const playing = own.filter((e) => e[1] !== null);
88
+ const lead = playing[0]?.[1];
89
+ if (!lead)
90
+ return null;
91
+ if (!p.lines?.length)
92
+ return lead;
93
+ const lines = playing.map(([s, b]) => ({
94
+ name: s.name ?? "",
95
+ line: b.line,
96
+ slots: b.slots,
97
+ ...(b.words && { words: b.words }),
98
+ }));
99
+ return { ...lead, lines };
100
+ }
101
+ /** A zipped bar of streams as a bar of parts; with one part shown, its lines sit on the bar itself. */
102
+ function foldBar(bar, streams, shown) {
103
+ const each = bar.parts ?? [];
104
+ const parts = shown.map((p, i) => partOf(p, streams.flatMap((s, j) => (s.part === i ? [[s, each[j] ?? null]] : []))));
105
+ const { parts: _p, words: _w, tacet: _t, ...shared } = bar;
106
+ const lead = parts[0];
107
+ const top = lead
108
+ ? { ...shared, line: lead.line, slots: lead.slots, ...(lead.words && { words: lead.words }) }
109
+ : bar;
110
+ if (shown.length > 1)
111
+ return { ...top, parts };
112
+ const { parts: _q, ...alone } = top;
113
+ return lead?.lines ? { ...alone, lines: lead.lines } : alone;
114
+ }
115
+ function foldEvents(events, streams, shown) {
116
+ return events.map((e) => {
117
+ if (e.kind === "bar")
118
+ return { kind: "bar", bar: foldBar(e.bar, streams, shown) };
119
+ if (e.kind === "open")
120
+ return { ...e, events: foldEvents(e.events, streams, shown) };
121
+ return e;
122
+ });
123
+ }
124
+ /** A part's own bars from a folded bar: tacet where none of its lines plays. */
125
+ function partView(b, i, shown) {
126
+ if (shown === 1)
127
+ return b;
128
+ const own = b.parts?.[i];
129
+ return own ? { ...b, line: own.line, slots: own.slots } : { ...b, slots: [], tacet: true };
130
+ }
131
+ /** The pedal warnings of each part that writes lines, walked on the part, not one line (grammar 2.9, 7.6). */
132
+ function linedPedalWarnings(events, shown) {
133
+ const bars = flattenBars(events);
134
+ return shown.flatMap((p, i) => p.lines?.length ? pedalWarnings(bars.map((b) => partView(b, i, shown.length))) : []);
135
+ }
136
+ /**
137
+ * Parts and their lines: each stream projected and played, zipped into one
138
+ * timeline, then folded into the parts shown (grammar 7.4, 7.6).
139
+ */
140
+ function playStreams(lines, parts, shown) {
141
+ const streams = streamsOf(shown);
142
+ const played = streams.map((s) => expand(projectPart(lines, parts, s.label, s.name), s.name === null ? s.label : `${s.label}.${s.name}`, streams.length, s.name === null));
84
143
  const diagnostics = mergeReports(played.map((p) => p.diagnostics));
85
- const events = zipEvents(played.map((p) => p.events), (d) => diagnostics.push(d));
144
+ const zipped = zipEvents(played.map((p) => p.events), (d) => diagnostics.push(d));
145
+ const events = foldEvents(zipped, streams, shown);
146
+ diagnostics.push(...linedPedalWarnings(events, shown));
86
147
  return { events, sections: played[0]?.sections ?? [], diagnostics };
87
148
  }
149
+ const lined = (parts) => parts.some((p) => p.lines?.length);
88
150
  /** Read a whole barmark chart: the document as written and the bars in play order. Never throws. */
89
151
  export function parseChart(text) {
90
152
  const doc = readDocument(text);
91
- const played = doc.parts.length > 1 ? playParts(doc.lines, doc.parts) : expand(doc.lines);
153
+ const played = doc.parts.length > 1 || lined(doc.parts)
154
+ ? playStreams(doc.lines, doc.parts, doc.parts)
155
+ : expand(doc.lines);
92
156
  return {
93
157
  title: doc.title,
94
158
  part: doc.part,
95
159
  parts: doc.parts,
160
+ credits: doc.credits,
96
161
  lines: doc.lines,
97
162
  events: played.events,
98
163
  bars: flattenBars(played.events),
@@ -100,18 +165,39 @@ export function parseChart(text) {
100
165
  diagnostics: sortDiagnostics([...doc.diagnostics, ...played.diagnostics]),
101
166
  };
102
167
  }
168
+ /** What an extract holds and plays: one of the part's lines, the part with its lines, or the part. */
169
+ function extractOf(doc, part, lineName) {
170
+ const label = part.label ?? "";
171
+ if (lineName !== undefined) {
172
+ const name = part.lines?.find((n) => n.toLowerCase() === lineName.toLowerCase());
173
+ if (!name)
174
+ return null;
175
+ const lines = projectPart(doc.lines, doc.parts, label, name);
176
+ return { lines, played: expand(lines, `${label}.${name}`) };
177
+ }
178
+ if (part.lines?.length)
179
+ return {
180
+ lines: projectPartLines(doc.lines, label),
181
+ played: playStreams(doc.lines, doc.parts, [part]),
182
+ };
183
+ const lines = doc.parts.length > 1 ? projectPart(doc.lines, doc.parts, label) : doc.lines;
184
+ return { lines, played: expand(lines, part.label) };
185
+ }
103
186
  /**
104
187
  * One part of a chart as a single-part chart (grammar 7.4): the tutti bars,
105
- * its own bars, and `N.C.` marked `tacet` where it rests. Null when the
106
- * chart declares no part with that label. Never throws.
188
+ * its own bars, and `N.C.` marked `tacet` where it rests. With `lineName`,
189
+ * one of the part's lines alone (grammar 7.6), as a converter writes each
190
+ * line: the part's first line also plays its bare and tutti lines, and a
191
+ * line rests where it isn't written. Null when the chart declares no part
192
+ * with that label, or the part no line of that name. Never throws.
107
193
  */
108
- export function extractPart(text, label) {
194
+ export function extractPart(text, label, lineName) {
109
195
  const doc = readDocument(text);
110
196
  const part = doc.parts.find((p) => p.label?.toLowerCase() === label.toLowerCase());
111
- if (!part)
197
+ const extract = part ? extractOf(doc, part, lineName) : null;
198
+ if (!part || !extract)
112
199
  return null;
113
- const lines = doc.parts.length > 1 ? projectPart(doc.lines, doc.parts, label) : doc.lines;
114
- const played = expand(lines, part.label);
200
+ const { lines, played } = extract;
115
201
  const kept = new Set(lines.map((l) => l.line));
116
202
  // A stand-in may sit on another part's line; that part's problems are not this one's.
117
203
  for (const l of doc.lines)
@@ -121,6 +207,7 @@ export function extractPart(text, label) {
121
207
  title: doc.title,
122
208
  part,
123
209
  parts: [part],
210
+ credits: doc.credits,
124
211
  lines,
125
212
  events: played.events,
126
213
  bars: flattenBars(played.events),
@@ -0,0 +1,3 @@
1
+ import type { Part } from "./types.js";
2
+ /** A `part:` line's label, name and attributes, or why it has none (grammar 7.3). */
3
+ export declare function readPart(text: string): Part | string | null;
@@ -0,0 +1,73 @@
1
+ import { DIRECTIVE_AFTER } from "./directives.js";
2
+ import { CLEF_NAMES, instrumentInfo, nearInstruments, } from "./instruments.js";
3
+ /** A `part:` line's label, name and attributes, or why it has none (grammar 7.3). */
4
+ export function readPart(text) {
5
+ const m = /^part\s*:(.*)$/i.exec(text);
6
+ if (!m)
7
+ return null;
8
+ const found = splitAttributes((m[1] ?? "").trim().replace(/\s+/g, " "));
9
+ if (typeof found === "string")
10
+ return found;
11
+ const attributes = readAttributes(found.attributes);
12
+ if (typeof attributes === "string")
13
+ return attributes;
14
+ const named = readName(found.value);
15
+ return typeof named === "string" ? named : { ...named, ...attributes };
16
+ }
17
+ /** The label and name before any attributes. */
18
+ function readName(value) {
19
+ if (DIRECTIVE_AFTER.test(value))
20
+ return "part: goes on a line of its own; the name runs to the end of the line";
21
+ const labelled = /^([^\s=]*)\s*=\s*(.*)$/.exec(value);
22
+ if (!labelled)
23
+ return value ? { name: value } : "part: needs a name";
24
+ const [, label, name] = labelled;
25
+ if (!label)
26
+ return "part: needs a label before =";
27
+ if (/^[|#@0-9]/.test(label))
28
+ return "a part label can't start with |, #, @ or a digit";
29
+ return name ? { label, name } : "part: needs a name after the label";
30
+ }
31
+ const ATTRIBUTE = /,\s*(instrument|clef)\s*:\s*([^,]*)$/i;
32
+ /** `, instrument: …` and `, clef: …` peeled off the end of the line, in either order. */
33
+ function splitAttributes(text) {
34
+ let value = text;
35
+ const attributes = new Map();
36
+ for (let m = ATTRIBUTE.exec(value); m; m = ATTRIBUTE.exec(value)) {
37
+ const name = (m[1] ?? "").toLowerCase();
38
+ if (attributes.has(name))
39
+ return `part: names its ${name} once`;
40
+ attributes.set(name, (m[2] ?? "").trim());
41
+ value = value.slice(0, m.index).trim();
42
+ }
43
+ return { value, attributes };
44
+ }
45
+ /** The instrument and clef written, each checked against its list. */
46
+ function readAttributes(written) {
47
+ const instrument = readInstrument(written.get("instrument"));
48
+ if (typeof instrument === "string")
49
+ return instrument;
50
+ const clef = written.get("clef")?.toLowerCase();
51
+ if (clef === undefined)
52
+ return instrument ? { instrument: instrument.name } : {};
53
+ const problem = clefProblem(clef, instrument?.staves ?? 1);
54
+ if (problem)
55
+ return problem;
56
+ return { ...(instrument && { instrument: instrument.name }), clef: clef };
57
+ }
58
+ /** The listed instrument written, null when none is, or why it isn't one. */
59
+ function readInstrument(name) {
60
+ if (name === undefined)
61
+ return null;
62
+ return instrumentInfo(name) ?? unknownInstrument(name);
63
+ }
64
+ function clefProblem(clef, staves) {
65
+ if (!CLEF_NAMES.includes(clef))
66
+ return `${clef || "an empty clef"} is not a clef; write ${CLEF_NAMES.join(", ")}`;
67
+ return staves === 2 ? "a keyboard has a treble and a bass staff; leave clef: out" : null;
68
+ }
69
+ function unknownInstrument(name) {
70
+ const near = nearInstruments(name);
71
+ const hint = near.length ? `: did you mean ${near.join(" or ")}?` : "";
72
+ return `${name || "an empty name"} is not an instrument barmark knows${hint}`;
73
+ }
@@ -1,7 +1,12 @@
1
- import type { Line, Part } from "./types.js";
1
+ import type { DeclaredPart, Line } from "./types.js";
2
2
  /**
3
3
  * One part of a multi-part chart as a single-part chart's lines (grammar
4
4
  * 7.4): the tutti lines, the part's own lines, and a bar of `N.C.` marked
5
- * `tacet` for each bar of a system it doesn't play. Never throws.
5
+ * `tacet` for each bar of a system it doesn't play. With `lineName`, one
6
+ * of the part's lines (grammar 7.6): the part's first line also plays
7
+ * its bare lines and the tutti lines, and a line rests (tacet) wherever
8
+ * it isn't written. Never throws.
6
9
  */
7
- export declare function projectPart(lines: Line[], parts: Part[], label: string): Line[];
10
+ export declare function projectPart(lines: Line[], parts: DeclaredPart[], label: string, lineName?: string | null): Line[];
11
+ /** One part's lines kept as written, labels and all, with a stand-in for each system it doesn't play: what an extract prints (grammar 7.6). */
12
+ export declare function projectPartLines(lines: Line[], label: string): Line[];
@@ -34,13 +34,22 @@ function standIn(system, at) {
34
34
  /** A part's own line, as a single-part chart writes it. */
35
35
  function unlabelled(l) {
36
36
  if (l.kind === "invalid") {
37
- const { part: _p, system: _s, ...rest } = l;
37
+ const { part: _p, lineName: _n, system: _s, ...rest } = l;
38
38
  return rest;
39
39
  }
40
- const { part: _p, system: _s, dropped: _d, ...rest } = l;
40
+ const { part: _p, lineName: _n, system: _s, dropped: _d, ...rest } = l;
41
41
  return rest;
42
42
  }
43
- const plays = (l, key) => l.part?.toLowerCase() === key && l.kind === "bars" && !l.dropped;
43
+ const plays = (l) => l?.kind === "bars" && !l.dropped;
44
+ /** The stream's own line in a system, if written. */
45
+ const ownLine = (system, s) => system.find((m) => m.part?.toLowerCase() === s.key &&
46
+ (s.name === null
47
+ ? true
48
+ : m.lineName === undefined
49
+ ? s.first
50
+ : m.lineName.toLowerCase() === s.name.toLowerCase()));
51
+ /** A tutti line as a stream other than its part's first hears it: tacet. */
52
+ const restingTutti = (l) => l.kind === "bars" ? { ...l, cells: l.cells.map(standInCell) } : l;
44
53
  const inSystem = (l) => (l.kind === "bars" || l.kind === "invalid") && l.system !== undefined;
45
54
  function systemsOf(lines) {
46
55
  const systems = new Map();
@@ -49,16 +58,18 @@ function systemsOf(lines) {
49
58
  systems.set(l.system, [...(systems.get(l.system) ?? []), l]);
50
59
  return systems;
51
60
  }
52
- /** What one line becomes in the part's chart: itself, its unlabelled self, a stand-in, or nothing. */
53
- function projectLine(l, key, systems) {
61
+ /** What one line becomes in the stream's chart: itself, its unlabelled self, a stand-in, or nothing. */
62
+ function projectLine(l, s, systems) {
54
63
  if (l.kind === "part")
55
- return l.label?.toLowerCase() === key ? l : null;
56
- return inSystem(l) ? projectSystemLine(l, key, systems.get(l.system) ?? []) : l;
64
+ return l.label?.toLowerCase() === s.key ? l : null;
65
+ if (inSystem(l))
66
+ return projectSystemLine(l, s, systems.get(l.system) ?? []);
67
+ return s.first ? l : restingTutti(l);
57
68
  }
58
- /** A system's line in one part's chart: the part's own line, a stand-in where it rests, or nothing. */
59
- function projectSystemLine(l, key, system) {
60
- const own = system.find((m) => m.part?.toLowerCase() === key);
61
- if (own === l && plays(l, key))
69
+ /** A system's line in one stream's chart: its own line, a stand-in where it rests, or nothing. */
70
+ function projectSystemLine(l, s, system) {
71
+ const own = ownLine(system, s);
72
+ if (own === l && plays(l))
62
73
  return unlabelled(l);
63
74
  const at = own ?? referenceOf(system) ?? system[0];
64
75
  return at === l ? standIn(system, l) : null;
@@ -66,12 +77,37 @@ function projectSystemLine(l, key, system) {
66
77
  /**
67
78
  * One part of a multi-part chart as a single-part chart's lines (grammar
68
79
  * 7.4): the tutti lines, the part's own lines, and a bar of `N.C.` marked
69
- * `tacet` for each bar of a system it doesn't play. Never throws.
80
+ * `tacet` for each bar of a system it doesn't play. With `lineName`, one
81
+ * of the part's lines (grammar 7.6): the part's first line also plays
82
+ * its bare lines and the tutti lines, and a line rests (tacet) wherever
83
+ * it isn't written. Never throws.
70
84
  */
71
- export function projectPart(lines, parts, label) {
85
+ export function projectPart(lines, parts, label, lineName = null) {
72
86
  if (!parts.length)
73
87
  return lines;
74
88
  const key = label.toLowerCase();
89
+ const part = parts.find((p) => p.label?.toLowerCase() === key);
90
+ const first = part?.lines?.[0];
91
+ const s = { key, name: lineName, first: lineName === null || lineName === first };
75
92
  const systems = systemsOf(lines);
76
- return lines.map((l) => projectLine(l, key, systems)).filter((l) => l !== null);
93
+ return lines.map((l) => projectLine(l, s, systems)).filter((l) => l !== null);
94
+ }
95
+ /** One part's lines kept as written, labels and all, with a stand-in for each system it doesn't play: what an extract prints (grammar 7.6). */
96
+ export function projectPartLines(lines, label) {
97
+ const key = label.toLowerCase();
98
+ const systems = systemsOf(lines);
99
+ return lines
100
+ .map((l) => {
101
+ if (l.kind === "part")
102
+ return l.label?.toLowerCase() === key ? l : null;
103
+ if (!inSystem(l))
104
+ return l;
105
+ const system = systems.get(l.system) ?? [];
106
+ const own = system.filter((m) => m.part?.toLowerCase() === key);
107
+ if (own.length)
108
+ return own.includes(l) ? l : null;
109
+ const at = referenceOf(system) ?? system[0];
110
+ return at === l ? standIn(system, l) : null;
111
+ })
112
+ .filter((l) => l !== null);
77
113
  }
@@ -0,0 +1,5 @@
1
+ import type { ChartDiagnostic, PlayedBar } from "./types.js";
2
+ /** Whether the pedal is down at the end of each slot of each bar, in play order. The chart's end lifts it. */
3
+ export declare function pedalStates(bars: PlayedBar[]): boolean[][];
4
+ /** A warning for each `*` played with the pedal already up, once per line. */
5
+ export declare function pedalWarnings(bars: PlayedBar[]): ChartDiagnostic[];
@@ -0,0 +1,44 @@
1
+ const pedalOf = (s) => (s.kind === "chord" ? s.pedal : undefined);
2
+ const membersOf = (s) => (s.kind === "group" ? s.members : [s]);
3
+ /**
4
+ * Walk a part's bars in play order with the pedal (grammar 2.9): `+`
5
+ * presses or changes it, `*` lifts it, and so do `--` and a tacet bar.
6
+ * `onRelease` hears each `*`, with whether the pedal was down.
7
+ */
8
+ function walk(bars, onRelease = () => { }) {
9
+ let down = false;
10
+ return bars.map((bar) => {
11
+ if (bar.tacet)
12
+ down = false;
13
+ return bar.slots.map((slot) => {
14
+ for (const m of membersOf(slot)) {
15
+ const pedal = pedalOf(m);
16
+ if (pedal === "release")
17
+ onRelease(bar, down);
18
+ if (pedal)
19
+ down = pedal === "press";
20
+ else if (m.kind === "silence")
21
+ down = false;
22
+ }
23
+ return down && !bar.tacet;
24
+ });
25
+ });
26
+ }
27
+ /** Whether the pedal is down at the end of each slot of each bar, in play order. The chart's end lifts it. */
28
+ export function pedalStates(bars) {
29
+ return walk(bars);
30
+ }
31
+ /** A warning for each `*` played with the pedal already up, once per line. */
32
+ export function pedalWarnings(bars) {
33
+ const lines = new Set();
34
+ walk(bars, (bar, wasDown) => {
35
+ if (!wasDown)
36
+ lines.add(bar.line);
37
+ });
38
+ return [...lines].map((line) => ({
39
+ line,
40
+ severity: "warning",
41
+ message: "* lifts the pedal, and it is already up here",
42
+ token: "*",
43
+ }));
44
+ }
@@ -44,14 +44,16 @@ export function reduceSlots(slots, beats) {
44
44
  const SYMBOLS = { hold: "/", nc: "N.C.", silence: "--", unknown: "?" };
45
45
  const PUSHES = { eighth: "<", sixteenth: "<<" };
46
46
  const ARTICULATIONS = { accent: ">", hit: "^" };
47
+ const PEDALS = { press: "+", release: "*" };
47
48
  /** A slot's leading marks: its push, then its articulation (grammar 2.7, 2.8). */
48
49
  function printMarks(s) {
49
50
  const push = "push" in s && s.push ? PUSHES[s.push] : "";
50
- return push + (s.kind === "chord" && s.articulation ? ARTICULATIONS[s.articulation] : "");
51
+ const pedal = s.kind === "chord" && s.pedal ? PEDALS[s.pedal] : "";
52
+ return pedal + push + (s.kind === "chord" && s.articulation ? ARTICULATIONS[s.articulation] : "");
51
53
  }
52
54
  function printSimple(s) {
53
55
  const body = s.kind === "chord" ? s.chord.canonical + (s.voicing?.canonical ?? "") : SYMBOLS[s.kind];
54
- return printMarks(s) + body;
56
+ return printMarks(s) + body + (s.dotted ? "." : "");
55
57
  }
56
58
  /** A slot in canonical spelling; a group's members are joined with `_`. */
57
59
  export function printSlot(s) {
@@ -147,7 +149,9 @@ export function printLine(l, beats = []) {
147
149
  case "directive":
148
150
  return printDirectives(l.set);
149
151
  case "part":
150
- return `part: ${l.label ? `${l.label} = ` : ""}${l.name}`;
152
+ return `part: ${l.label ? `${l.label} = ` : ""}${l.name}${l.instrument ? `, instrument: ${l.instrument}` : ""}${l.clef ? `, clef: ${l.clef}` : ""}`;
153
+ case "credit":
154
+ return `${l.role}: ${l.text}`;
151
155
  case "bars":
152
156
  return joinPieces(barPieces(l, beats));
153
157
  default:
@@ -162,13 +166,24 @@ export function printLine(l, beats = []) {
162
166
  export function printChart(text) {
163
167
  return printParsed(text, parseChart(text));
164
168
  }
169
+ /** A labelled line's label as printed: the part's, and its line's name (`Pno.RH`, grammar 7.6). */
170
+ const labelOf = (l) => `${l.part ?? ""}${l.lineName === undefined ? "" : `.${l.lineName}`}`;
171
+ const labelsOf = (p) => [
172
+ p.label ?? "",
173
+ ...(p.lines ?? []).map((n) => `${p.label}.${n}`),
174
+ ];
175
+ /** Score order: by part, then by the part's line, a bare line first. */
176
+ function scoreOf(l, parsed) {
177
+ const at = parsed.parts.findIndex((p) => p.label === l.part);
178
+ const line = l.lineName === undefined ? -1 : (parsed.parts[at]?.lines ?? []).indexOf(l.lineName);
179
+ return at * 10 + line + 1;
180
+ }
165
181
  /** A system's lines in score order, labels padded and pipes lined up (section 8, grammar 7.4). */
166
182
  function alignSystem(system, parsed, beatsFor, edit) {
167
- const score = (l) => parsed.parts.findIndex((p) => p.label === l.part);
168
- const width = Math.max(...parsed.parts.map((p) => p.label?.length ?? 0));
183
+ const width = Math.max(...parsed.parts.flatMap(labelsOf).map((label) => label.length));
169
184
  const pieces = [...system]
170
- .sort((a, b) => score(a) - score(b))
171
- .map((l) => ({ label: l.part ?? "", ...barPieces(edit(l), beatsFor(l)) }));
185
+ .sort((a, b) => scoreOf(a, parsed) - scoreOf(b, parsed))
186
+ .map((l) => ({ label: labelOf(l), ...barPieces(edit(l), beatsFor(l)) }));
172
187
  const columns = pieces[0]?.cells.map((_, i) => Math.max(...pieces.map((p) => p.cells[i]?.length ?? 0)));
173
188
  return pieces.map((p) => `${p.label.padEnd(width)} ${joinPieces({ ...p, cells: p.cells.map((c, i) => c.padEnd(columns?.[i] ?? 0)) })}`.trimEnd());
174
189
  }
@@ -187,7 +202,7 @@ function systemTexts(parsed, errored, beatsFor, edit) {
187
202
  // A system with an error is neither sorted nor padded, so the error's line stays where it was written.
188
203
  const printed = valid.length === lines.length
189
204
  ? alignSystem(valid, parsed, beatsFor, edit)
190
- : valid.map((l) => `${l.part} ${printLine(edit(l), beatsFor(l))}`);
205
+ : valid.map((l) => `${labelOf(l)} ${printLine(edit(l), beatsFor(l))}`);
191
206
  for (const [i, l] of valid.entries())
192
207
  texts.set(l.line, printed[i] ?? "");
193
208
  }
@@ -106,7 +106,7 @@ export function pairRepeats(lines, error) {
106
106
  for (const l of lines) {
107
107
  if (l.kind === "bars" && l.ending)
108
108
  takeEnding(st, l, error);
109
- else if (st.endings && l.kind === "text")
109
+ else if (st.endings && (l.kind === "text" || l.kind === "credit"))
110
110
  st.endings.between.push({ line: l, repeat: null });
111
111
  else {
112
112
  finish();
@@ -0,0 +1,6 @@
1
+ import type { SimpleSlot } from "./types.js";
2
+ /**
3
+ * How a group divides its slot (grammar 2.2), as fractions summing to 1:
4
+ * equally, or 3:1 (1:3) when one member of a pair is dotted.
5
+ */
6
+ export declare function memberShares(members: SimpleSlot[]): number[];