barmark 0.22.0 → 0.23.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,100 @@ Releases follow the process in [RELEASING.md](RELEASING.md).
9
9
 
10
10
  ## [Unreleased]
11
11
 
12
+ ## [0.23.1] - 2026-11-10
13
+
14
+ ### Changed
15
+
16
+ - **Words on a rehearsal mark's cell get a suggestion.** They are still
17
+ an error (`| @B "Play 3 times" C |`), now with a suggestion, as a chord
18
+ on a mark has: the mark a cell of its own and the words on the bar
19
+ (`| @B | "Play 3 times" C |`). There is none when no slot is left for
20
+ the words or the cell has a one-bar meter (stem-shovel issue 16, ask 7).
21
+
22
+ ## [0.23.0] - 2026-11-10
23
+
24
+ Grammar changes: an unreadable slot keeps its bar, stacked chord
25
+ spellings read, and an ending may continue onto the lines after it
26
+ (Kevin, 2026-11-10). Implements the
27
+ [grammar v0.1 draft](https://github.com/kevinpeckham/barmark/blob/main/docs/grammar-v0.1-draft.md).
28
+
29
+ ### Added
30
+
31
+ - **Stacked chord spellings read, with a warning** (grammar 3, A.5;
32
+ stem-shovel issue 16). Notation programs print alterations run together
33
+ ("D6 add9 omit5"): items run together in one parenthesis
34
+ (`D6(omit5add9)`, `D6(no5add9)`, `C7(b9#11)`) and a bare `omit`/`no`
35
+ trailing the chord's name, after the quality however it is spelled and
36
+ before any parenthesis or slash bass (`Gadd9omit3`, `Gomit5`, `Gno5`,
37
+ `G-7omit5`, `CΔno3`; not `Cno5maj7` or `Cno3add9`) now read as their
38
+ comma-separated form instead of being unreadable. The warning's
39
+ `suggestion` is that form (`D6(omit5,add9)`, `Gadd9(omit3)`,
40
+ `G(omit5)`); the printer writes the canonical form (`D6(9,no5)`), so
41
+ `format` fixes them. Items that are wrong on their own stay errors
42
+ (`C(omit5omit5)`). A chord warning's `suggestion` now reaches the
43
+ chart's diagnostic.
44
+ - **An altered fifth before the parenthesis gets a suggestion**:
45
+ `F#b5(omit3)` is still an error (grammar 3 keeps `Ab5` the A♭ power
46
+ chord), now suggesting `F#(b5,omit3)`. Where the root's accidental could
47
+ be the fifth's, there is no suggestion, and the message says the symbol
48
+ is ambiguous when the fifth reading would itself read (`Gb5(omit3)`,
49
+ as `G(b5,omit3)`; not `Gb5(no7)`).
50
+ - **An ending may continue onto the lines after it** (grammar 5.1, Kevin
51
+ 2026-11-10, stem-shovel issue #16). An ending not closed by `:|` on its
52
+ own line continues through the plain `|` lines after it, up to its `:|`
53
+ or the next ending: `|1 G | A | B | C |` then `| D :|` is a five-bar
54
+ first ending, so a chart keeps four bars a row. The last ending still
55
+ ends at its own line. Each continuation line carries the ending's passes
56
+ as the new optional `continues` on its bar line in the parse tree (A.7),
57
+ and plays on that ending's passes only. Text, credit, lyric-row and
58
+ `---` lines may sit between an ending's lines; a heading, a directive
59
+ line, a `|:` line or a line that can't be read ends it, and a directive
60
+ line that stops an ending continuing is an error naming it. Only the
61
+ endings of a paired repeat continue. A chart that
62
+ read cleanly before reads the same; an ending before the last that runs
63
+ into the next ending with no `:|` now gives one error, "an ending before
64
+ the last goes back with :|", on its first line, where it gave two.
65
+ - **`printedAsWritten(parse)`** and **`unreadSlots(line)`**: the lines the
66
+ printer prints as written (spec §8), and a bar line's unreadable slots,
67
+ so a renderer draws what the printer prints.
68
+
69
+ ### Changed
70
+
71
+ - **An unreadable slot is kept as unknown harmony with its text** (grammar
72
+ principle 4, 2.3, 3). An unknown chord symbol (`CM7`, `CSus4`, `C69`),
73
+ a bad note set (`{H}`), a voicing note not in its chord, a syllable on a
74
+ chord name, a lone `-`, a mark that can't be read (`<<<C`, `+?`) or a
75
+ misplaced or bad dot (`| C. |`, `C._D._E`) is
76
+ still an error with the same message, token and suggestion, so `check`
77
+ still fails; but the slot becomes `{ kind: "unknown", text }` and the
78
+ line keeps its bars, so a chart plays as long as it is written. Only a
79
+ bar line whose structure can't be read (a stray `|:` or `:|`, a bad
80
+ ending or `x N`, an empty group member, `%`, `...`, a direction or a
81
+ mark sharing a cell, an empty cell, a bad `[n/d]`, an unclosed quote)
82
+ is still excluded.
83
+ Before, any error dropped the whole line.
84
+ - **`SimpleSlot`'s `unknown` has an optional `text`** (A.7): the slot as
85
+ written, absent for a written `?`. `printSlot` and `printLine` print it
86
+ as written, a dotted member's dot back in its place.
87
+ - **`format` prints a bar line whose only errors are unreadable slots in
88
+ canonical form** (spec §8), each slot's text as written. A line
89
+ excluded for its structure, or with any other error, still prints as
90
+ written.
91
+ - **`transposeChart` moves the readable chords on a line with an
92
+ unreadable slot** (Kevin, 2026-11-10): `key: C`, `| C | CM7 | G |` to D
93
+ is `| D | CM7 | A |`, with the warning "CM7 can't move: it can't be
94
+ read, so it stays as written" on the slot. A line excluded for its
95
+ structure still stays as written, with "not transposed: this line has
96
+ an error".
97
+ - A part's notes line (7.6) with an unreadable note set has that error
98
+ alone, not a second one for harmony on the line.
99
+
100
+ ### Fixed
101
+
102
+ - A chord symbol with many `add` tones in its parenthesis read in time
103
+ quadratic in its length (20,000 items took seconds); reading a chord
104
+ symbol is now linear.
105
+
12
106
  ## [0.22.0] - 2026-11-09
13
107
 
14
108
  A grammar change: a chart's pickup is bar 0 (2.4), which now defines a
@@ -760,7 +854,9 @@ The first working release: the reference parser and printer for the
760
854
 
761
855
  - **A placeholder package that holds the `barmark` name** while the spec and parser are written.
762
856
 
763
- [Unreleased]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.22.0...HEAD
857
+ [Unreleased]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.23.1...HEAD
858
+ [0.23.1]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.23.0...barmark-v0.23.1
859
+ [0.23.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.22.0...barmark-v0.23.0
764
860
  [0.22.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.21.0...barmark-v0.22.0
765
861
  [0.21.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.20.0...barmark-v0.21.0
766
862
  [0.20.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.19.1...barmark-v0.20.0
@@ -1,7 +1,9 @@
1
- import type { Cell, ChartDiagnostic, Line, Meter, Repeat, Slot, Words } from "./types.js";
1
+ import type { Cell, ChartDiagnostic, Line, Meter, Repeat, SimpleSlot, Slot, Words } from "./types.js";
2
2
  type BarsLine = Extract<Line, {
3
3
  kind: "bars";
4
4
  }>;
5
+ /** Each simple slot of these cells, a group's members each. */
6
+ export declare const simpleSlots: (cells: Cell[]) => SimpleSlot[];
5
7
  /** Whether a cell is a bar: `...`, a direction and a rehearsal mark mark a place between bars. */
6
8
  export declare const isBar: (c: Cell) => c is {
7
9
  kind: "slots";
@@ -28,8 +30,10 @@ export declare function repeatTail(text: string, boundary: boolean): {
28
30
  export declare function misplacedRepeat(token: string): string | null;
29
31
  /**
30
32
  * One bar line: cells between pipes, each cell's slots, the `|:` and `:|`
31
- * marks and an `x N` tail. Any error drops the whole line (`bars` is null);
32
- * `written` still says how many bars it writes.
33
+ * marks and an `x N` tail. An error in its structure drops the whole line
34
+ * (`bars` is null); `written` still says how many bars it writes. A slot
35
+ * that can't be read is an error too, but keeps its place as unknown
36
+ * harmony with its text (grammar principle 4).
33
37
  */
34
38
  export declare function parseBarLine(text: string, line: number): {
35
39
  bars: BarsLine | null;
@@ -5,6 +5,8 @@ import { isDirectionWord, readDirection } from "./direction.js";
5
5
  import { parseMeter } from "./directives.js";
6
6
  import { readSyllable, splitSyllable } from "./syllable.js";
7
7
  const FERMATA = new Set(["...", "…"]);
8
+ /** Each simple slot of these cells, a group's members each. */
9
+ export const simpleSlots = (cells) => cells.flatMap((c) => c.kind === "slots" ? c.slots.flatMap((s) => (s.kind === "group" ? s.members : [s])) : []);
8
10
  /** Whether a cell is a bar: `...`, a direction and a rehearsal mark mark a place between bars. */
9
11
  export const isBar = (c) => c.kind === "slots" || c.kind === "simile";
10
12
  const QUOTES = new Set(['"', "“", "”", "„"]);
@@ -422,85 +424,47 @@ function rehearsalCell(bare, meter, words) {
422
424
  problem: "a rehearsal mark is @ and a label of letters and digits, like @B or @17",
423
425
  token: mark,
424
426
  };
427
+ const others = withWords(list, words, at);
428
+ // The mark's own cell, the rest on the bar; with no slot left the words have no bar to go on.
429
+ const split = list.length > 1 && !meter ? { suggestion: `| ${mark} | ${others} |` } : {};
425
430
  if (words.length)
426
- return { problem: "words go on a bar, not on a rehearsal mark", token: mark };
431
+ return { problem: "words go on a bar, not on a rehearsal mark", token: mark, ...split };
427
432
  if (meter)
428
433
  return { problem: "a one-bar meter cannot go on a rehearsal mark", token: mark };
429
434
  if (list.length === 1)
430
435
  return { cell: { kind: "rehearsal", label: mark.slice(1) } };
431
- const others = list.filter((_, i) => i !== at).join(" ");
432
- return {
433
- problem: "a rehearsal mark is a cell of its own",
434
- token: mark,
435
- suggestion: `| ${mark} | ${others} |`,
436
- };
436
+ return { problem: "a rehearsal mark is a cell of its own", token: mark, ...split };
437
+ }
438
+ /** A cell's tokens with its words back in their places, in straight quotes, leaving out token `skip`. */
439
+ function withWords(list, words, skip) {
440
+ const quoted = (i) => words.filter((w) => w.at === i).map((w) => `"${w.text}"`);
441
+ const out = list.flatMap((t, i) => [...quoted(i), ...(i === skip ? [] : [t])]);
442
+ return [...out, ...quoted(list.length)].join(" ");
437
443
  }
444
+ /** An unreadable slot (grammar principle 4): unknown harmony keeping what the author wrote. */
445
+ const unreadable = (text, dotted) => ({
446
+ kind: "unknown",
447
+ text,
448
+ ...(dotted ? { dotted: true } : {}),
449
+ });
450
+ /** A sung member's text without its rhythm's dot: `{H}.:la` is `{H}:la`. */
451
+ const undotted = ({ note, syllable }) => `${note.slice(0, -1)}${syllable === null ? "" : `:${syllable}`}`;
438
452
  /**
439
- * One bar line: cells between pipes, each cell's slots, the `|:` and `:|`
440
- * marks and an `x N` tail. Any error drops the whole line (`bars` is null);
441
- * `written` still says how many bars it writes.
453
+ * The reader of one slot token: a simple slot or a `_` group of them. A
454
+ * slot it can't read is an error and becomes unknown harmony with its
455
+ * text (`unread`), a misplaced or bad dot included; a misplaced `%`,
456
+ * `...`, direction or `x N`, or an empty member is an error in the bar
457
+ * line's structure (`error`).
442
458
  */
443
- export function parseBarLine(text, line) {
444
- const diagnostics = [];
445
- let listed = 0;
446
- const add = (d) => {
447
- listed++;
448
- if (listed <= MAX_LINE_DIAGNOSTICS)
449
- diagnostics.push(d);
450
- else if (listed === MAX_LINE_DIAGNOSTICS + 1)
451
- diagnostics.push({
452
- line,
453
- severity: "error",
454
- message: "further problems on this line are not listed",
455
- token: "",
456
- });
457
- };
458
- const error = (message, token, suggestion) => {
459
- add({ line, severity: "error", message, token, ...(suggestion ? { suggestion } : {}) });
460
- return null;
461
- };
462
- const warn = (message, token) => add({ line, severity: "warning", message, token });
463
- let body = text.trim();
464
- let repeat = null;
465
- const lastPipe = body.lastIndexOf("|");
466
- const tail = repeatTail(body.slice(lastPipe + 1), true);
467
- if (tail) {
468
- body = body.slice(0, lastPipe + 1) + tail.rest;
469
- repeat = readRepeat(tail.count, line, diagnostics);
470
- }
471
- const leading = readEnding(body);
472
- body = leading.body;
473
- const ending = leading.ending;
474
- if (leading.bad)
475
- error(ENDING_FORM, leading.bad);
476
- const opens = body.startsWith("|:");
477
- if (opens)
478
- body = `|${body.slice(2)}`;
479
- const closes = body.endsWith(":|");
480
- if (closes)
481
- body = `${body.slice(0, -2)}|`;
482
- const written = barsWritten(body);
483
- const stray = strayEnding(body);
484
- if (stray)
485
- error(...stray);
486
- if (body.includes(":|") || body.includes("|:"))
487
- error("|: must open a bar line and :| must close one", body.includes(":|") ? ":|" : "|:");
488
- // A misplaced mark makes the cells unreadable: report it once, not again as chords.
489
- if (diagnostics.some((d) => d.severity === "error"))
490
- return { bars: null, written, diagnostics };
491
- const parts = body.split("|").slice(1);
492
- if (parts.at(-1)?.trim() === "")
493
- parts.pop();
494
- else
495
- warn("missing trailing |", parts.at(-1)?.trim() ?? "");
496
- const report = (p) => error(p.problem, p.token, p.suggestion);
459
+ function slotReader({ error, unread, warn, broken }) {
460
+ const report = (p) => unread(p.problem, p.token, p.suggestion);
497
461
  const simple = (token) => {
498
462
  if (token === "/")
499
463
  return { kind: "hold" };
500
464
  if (SILENCE.has(token))
501
465
  return { kind: "silence" };
502
466
  if (token === "-")
503
- return error("a lone - is not a slot; silence is --", token, "--");
467
+ return unread("a lone - is not a slot; silence is --", token, "--");
504
468
  if (token === "?") {
505
469
  warn("unknown harmony", token);
506
470
  return { kind: "unknown" };
@@ -524,14 +488,14 @@ export function parseBarLine(text, line) {
524
488
  return report(v);
525
489
  for (const r of v.warnings)
526
490
  for (const w of r.ok ? r.warnings : [])
527
- warn(w.message, w.token);
491
+ warn(w.message, w.token, w.suggestion);
528
492
  return { kind: "chord", chord: v.chord, voicing: v.voicing };
529
493
  }
530
494
  const r = brace === 0 ? parseNoteSet(token) : parseChord(token);
531
495
  if (!r.ok)
532
- return error(r.error.message, token, r.error.suggestion);
496
+ return unread(r.error.message, token, r.error.suggestion);
533
497
  for (const w of r.warnings)
534
- warn(w.message, w.token);
498
+ warn(w.message, w.token, w.suggestion);
535
499
  return { kind: "chord", chord: r.value };
536
500
  };
537
501
  /** A slot with its push and articulation, if written. */
@@ -563,35 +527,110 @@ export function parseBarLine(text, line) {
563
527
  const withSyllable = ({ note, syllable }, read) => {
564
528
  const written = `${note}:${syllable}`;
565
529
  if (syllable !== null && !note)
566
- return error(NOT_A_NOTE_SET, written);
530
+ return unread(NOT_A_NOTE_SET, written);
567
531
  const slot = read(note);
568
532
  if (syllable === null || !slot)
569
533
  return slot;
570
534
  const sung = sungOn(slot, syllable);
571
- return "problem" in sung ? error(sung.problem, written) : sung;
535
+ return "problem" in sung ? unread(sung.problem, written) : sung;
572
536
  };
573
- /** One slot token: a simple slot, or a `_` group of them. */
574
- const slotOf = (token) => {
575
- const members = groupMembers(token).map(splitSyllable);
576
- const dots = members.filter((m) => isDotted(m.note)).length;
577
- if (dots && (members.length !== 2 || dots > 1))
578
- return error(DOT_PLACE, token);
579
- const [only] = members;
580
- if (only && members.length === 1)
581
- return withSyllable(only, (n) => markedSlot(n, false));
582
- return groupOf(members, token);
537
+ /** A member as read, or as written when it can't be; null once the structure has broken. */
538
+ const keep = (split, read, written) => {
539
+ const slot = withSyllable(split, read);
540
+ if (slot || broken())
541
+ return slot;
542
+ return isDotted(split.note) ? unreadable(undotted(split), true) : unreadable(written, false);
583
543
  };
584
544
  const groupOf = (members, token) => {
585
545
  const out = [];
586
546
  for (const m of members) {
587
547
  const s = m.note || m.syllable !== null
588
- ? withSyllable(m, memberOf)
548
+ ? keep(m, memberOf, m.syllable === null ? m.note : `${m.note}:${m.syllable}`)
589
549
  : error("an empty member in a group", token);
590
550
  if (s)
591
551
  out.push(s);
592
552
  }
593
553
  return { kind: "group", members: out };
594
554
  };
555
+ return (token) => {
556
+ const members = groupMembers(token).map(splitSyllable);
557
+ const dots = members.filter((m) => isDotted(m.note)).length;
558
+ // A dot never changes the bar count: a misplaced one is the slot's error (Kevin, 2026-11-10).
559
+ if (dots && (members.length !== 2 || dots > 1))
560
+ return unread(DOT_PLACE, token) ?? unreadable(token, false);
561
+ const [only] = members;
562
+ if (only && members.length === 1)
563
+ return keep(only, (n) => markedSlot(n, false), token);
564
+ return groupOf(members, token);
565
+ };
566
+ }
567
+ /**
568
+ * One bar line: cells between pipes, each cell's slots, the `|:` and `:|`
569
+ * marks and an `x N` tail. An error in its structure drops the whole line
570
+ * (`bars` is null); `written` still says how many bars it writes. A slot
571
+ * that can't be read is an error too, but keeps its place as unknown
572
+ * harmony with its text (grammar principle 4).
573
+ */
574
+ export function parseBarLine(text, line) {
575
+ const diagnostics = [];
576
+ let listed = 0;
577
+ let broken = false;
578
+ const add = (d) => {
579
+ listed++;
580
+ if (listed <= MAX_LINE_DIAGNOSTICS)
581
+ diagnostics.push(d);
582
+ else if (listed === MAX_LINE_DIAGNOSTICS + 1)
583
+ diagnostics.push({
584
+ line,
585
+ severity: "error",
586
+ message: "further problems on this line are not listed",
587
+ token: "",
588
+ });
589
+ };
590
+ const unread = (message, token, suggestion) => {
591
+ add({ line, severity: "error", message, token, ...(suggestion ? { suggestion } : {}) });
592
+ return null;
593
+ };
594
+ const error = (message, token, suggestion) => {
595
+ broken = true;
596
+ return unread(message, token, suggestion);
597
+ };
598
+ const warn = (message, token, suggestion) => add({ line, severity: "warning", message, token, ...(suggestion ? { suggestion } : {}) });
599
+ let body = text.trim();
600
+ let repeat = null;
601
+ const lastPipe = body.lastIndexOf("|");
602
+ const tail = repeatTail(body.slice(lastPipe + 1), true);
603
+ if (tail) {
604
+ body = body.slice(0, lastPipe + 1) + tail.rest;
605
+ repeat = readRepeat(tail.count, line, diagnostics);
606
+ }
607
+ const leading = readEnding(body);
608
+ body = leading.body;
609
+ const ending = leading.ending;
610
+ if (leading.bad)
611
+ error(ENDING_FORM, leading.bad);
612
+ const opens = body.startsWith("|:");
613
+ if (opens)
614
+ body = `|${body.slice(2)}`;
615
+ const closes = body.endsWith(":|");
616
+ if (closes)
617
+ body = `${body.slice(0, -2)}|`;
618
+ const written = barsWritten(body);
619
+ const stray = strayEnding(body);
620
+ if (stray)
621
+ error(...stray);
622
+ if (body.includes(":|") || body.includes("|:"))
623
+ error("|: must open a bar line and :| must close one", body.includes(":|") ? ":|" : "|:");
624
+ // A misplaced mark makes the cells unreadable: report it once, not again as chords.
625
+ if (diagnostics.some((d) => d.severity === "error"))
626
+ return { bars: null, written, diagnostics };
627
+ const parts = body.split("|").slice(1);
628
+ if (parts.at(-1)?.trim() === "")
629
+ parts.pop();
630
+ else
631
+ warn("missing trailing |", parts.at(-1)?.trim() ?? "");
632
+ const report = (p) => error(p.problem, p.token, p.suggestion);
633
+ const slotOf = slotReader({ error, unread, warn, broken: () => broken });
595
634
  const readCell = (raw) => {
596
635
  const rest = raw.trim();
597
636
  if (!rest)
@@ -620,9 +659,8 @@ export function parseBarLine(text, line) {
620
659
  if (parts.length === 0)
621
660
  error("a bar line needs at least one cell", text.trim());
622
661
  const cells = parts.map(readCell).filter((c) => c !== null);
623
- const failed = diagnostics.some((d) => d.severity === "error");
624
662
  return {
625
- bars: failed ? null : { kind: "bars", line, opens, closes, cells, repeat, ending },
663
+ bars: broken ? null : { kind: "bars", line, opens, closes, cells, repeat, ending },
626
664
  written,
627
665
  diagnostics,
628
666
  };
@@ -2,6 +2,7 @@ import { parseChord } from "../chords/parse.js";
2
2
  import { misplacedRepeat, parseBarLine, readRepeat, repeatTail } from "./barLine.js";
3
3
  import { creditsOf, nearCredit, readCredit } from "./credits.js";
4
4
  import { parseDirectiveLine } from "./directives.js";
5
+ import { continueEndings } from "./endingLines.js";
5
6
  import { checkLines } from "./lines.js";
6
7
  import { attachLyrics, readLyricRow } from "./lyricRows.js";
7
8
  import { readPart } from "./partLine.js";
@@ -363,14 +364,15 @@ export function readDocument(text) {
363
364
  const read = checkParts(lines, diagnostics);
364
365
  const grouped = groupParts(lines, read);
365
366
  const lyrics = attachLyrics(grouped.lines);
366
- diagnostics.push(...grouped.diagnostics, ...lyrics.diagnostics);
367
+ const ended = continueEndings(lyrics.lines);
368
+ diagnostics.push(...grouped.diagnostics, ...lyrics.diagnostics, ...ended.diagnostics);
367
369
  const { parts } = grouped;
368
370
  return {
369
371
  title,
370
372
  part: parts.length === 1 ? (parts[0] ?? null) : null,
371
373
  parts,
372
374
  credits: creditsOf(lines),
373
- lines: lyrics.lines,
375
+ lines: ended.lines,
374
376
  diagnostics,
375
377
  };
376
378
  }
@@ -0,0 +1,13 @@
1
+ import type { ChartDiagnostic, Line } from "./types.js";
2
+ /** Lines that may sit between endings, and between an ending's lines (grammar 5.1): they mean nothing to the timeline. */
3
+ export declare const BETWEEN_ENDINGS: Set<"bars" | "break" | "credit" | "directive" | "invalid" | "lyrics" | "part" | "section" | "text" | "title">;
4
+ /**
5
+ * Mark the plain bar lines that continue an ending onto further lines
6
+ * (grammar 5.1, Kevin's decision 2026-11-10): each gets the ending's
7
+ * passes as `continues`. Only an ending of a paired repeat continues, so
8
+ * an ending with no `|:` before it leaves a stray `:|` stray. Never throws.
9
+ */
10
+ export declare function continueEndings(lines: Line[]): {
11
+ lines: Line[];
12
+ diagnostics: ChartDiagnostic[];
13
+ };
@@ -0,0 +1,136 @@
1
+ /** Lines that may sit between endings, and between an ending's lines (grammar 5.1): they mean nothing to the timeline. */
2
+ export const BETWEEN_ENDINGS = new Set(["text", "credit", "lyrics", "break"]);
3
+ const inSystem = (l) => (l.kind === "bars" || l.kind === "invalid") && l.system !== undefined;
4
+ const systemOf = (l) => (l.kind === "bars" || l.kind === "invalid" ? l.system : undefined);
5
+ /** The chart's lines as units: each system's lines read as one, by its first line that reads and agrees. */
6
+ function unitsOf(lines) {
7
+ const units = [];
8
+ for (const l of lines) {
9
+ const last = units.at(-1);
10
+ const first = last?.lines[0];
11
+ if (last && first && inSystem(l) && systemOf(first) === systemOf(l))
12
+ last.lines.push(l);
13
+ else
14
+ units.push({ lines: [l], ref: l });
15
+ }
16
+ for (const u of units)
17
+ u.ref = u.lines.find((l) => l.kind === "bars" && !l.dropped) ?? u.lines[0];
18
+ return units;
19
+ }
20
+ const bars = (l) => (l.kind === "bars" ? l : null);
21
+ /** A bar line with no repeat start and no ending: one an ending can continue onto. */
22
+ const plain = (l) => l.kind === "bars" && !l.opens && !l.ending;
23
+ const startsEnding = (l) => l?.kind === "bars" && l.ending !== null;
24
+ /** The same lines, and directive lines too: what an ending would continue past if directives could sit in it. */
25
+ const PAST_DIRECTIVES = new Set([...BETWEEN_ENDINGS, "directive"]);
26
+ /** The first unit from `from` whose kind isn't one of `past`; reads only up to it. */
27
+ function nextHeard(units, from, past) {
28
+ let k = from;
29
+ while (k < units.length && past.has(units[k].ref.kind))
30
+ k++;
31
+ return units[k]?.ref;
32
+ }
33
+ /**
34
+ * The units an unclosed ending at `at` continues onto: the plain bar lines
35
+ * after it, up to its `:|` or the next ending, when another ending follows
36
+ * (grammar 5.1). The last ending has none, so it ends at its own line.
37
+ * `past` are the lines that may sit among them.
38
+ */
39
+ function continuation(units, at, past = BETWEEN_ENDINGS) {
40
+ const run = [];
41
+ for (let k = at + 1; k < units.length; k++) {
42
+ const ref = units[k].ref;
43
+ if (past.has(ref.kind))
44
+ continue;
45
+ if (startsEnding(ref))
46
+ return run;
47
+ if (!plain(ref))
48
+ return [];
49
+ run.push(k);
50
+ if (bars(ref)?.closes)
51
+ return startsEnding(nextHeard(units, k + 1, past)) ? run : [];
52
+ }
53
+ return [];
54
+ }
55
+ /** A directive line's own name, as its token: `time:`, `tempo:`. */
56
+ function directiveName(set) {
57
+ const first = Object.keys(set)[0] ?? "key";
58
+ const name = { tempoChange: "tempo", swingPercent: "feel" }[first] ?? first;
59
+ return `${name}:`;
60
+ }
61
+ /**
62
+ * The directive line that stopped an ending continuing, when without it
63
+ * the ending would have continued: named, beside the errors that follow
64
+ * (grammar 5.1). Null when nothing would have continued anyway.
65
+ */
66
+ function directiveInside(units, at, head) {
67
+ if (continuation(units, at).length || !continuation(units, at, PAST_DIRECTIVES).length)
68
+ return null;
69
+ for (let k = at + 1; k < units.length; k++) {
70
+ const ref = units[k].ref;
71
+ if (startsEnding(ref))
72
+ break;
73
+ if (ref.kind === "directive")
74
+ return {
75
+ line: ref.line,
76
+ severity: "error",
77
+ message: `a directive line ends the ending |${head.ending?.join(",")} above it; an ending's lines can't hold one`,
78
+ token: directiveName(ref.set),
79
+ };
80
+ }
81
+ return null;
82
+ }
83
+ /** Whether a `|:` is waiting for its `:|` after `l`: a heading or a `:|` ends it, a `|:` opens one. */
84
+ function stillOpen(open, l) {
85
+ if (l.kind === "section")
86
+ return false;
87
+ if (l.kind !== "bars")
88
+ return open;
89
+ return !l.closes && (open || l.opens);
90
+ }
91
+ /** Whether `l` is an ending of a paired repeat, moving the pairing past it. */
92
+ function paired(p, l) {
93
+ if (l.kind === "bars" && l.ending) {
94
+ p.endings = p.open || p.endings;
95
+ p.open = false;
96
+ return p.endings;
97
+ }
98
+ if (!(p.endings && BETWEEN_ENDINGS.has(l.kind))) {
99
+ p.endings = false;
100
+ p.open = stillOpen(p.open, l);
101
+ }
102
+ return false;
103
+ }
104
+ /**
105
+ * Mark the plain bar lines that continue an ending onto further lines
106
+ * (grammar 5.1, Kevin's decision 2026-11-10): each gets the ending's
107
+ * passes as `continues`. Only an ending of a paired repeat continues, so
108
+ * an ending with no `|:` before it leaves a stray `:|` stray. Never throws.
109
+ */
110
+ export function continueEndings(lines) {
111
+ const units = unitsOf(lines);
112
+ const marked = new Map();
113
+ const diagnostics = [];
114
+ const pairing = { open: false, endings: false };
115
+ for (let i = 0; i < units.length; i++) {
116
+ const ref = units[i].ref;
117
+ if (!paired(pairing, ref) || ref.kind !== "bars" || !ref.ending || ref.closes)
118
+ continue;
119
+ const run = continuation(units, i);
120
+ for (const k of run)
121
+ for (const l of units[k].lines)
122
+ marked.set(l, ref.ending);
123
+ const inside = directiveInside(units, i, ref);
124
+ if (inside)
125
+ diagnostics.push(inside);
126
+ // The lines it continues onto belong to the ending: the pairing goes on after them.
127
+ i = run.at(-1) ?? i;
128
+ }
129
+ if (!marked.size)
130
+ return { lines, diagnostics };
131
+ const out = lines.map((l) => {
132
+ const passes = marked.get(l);
133
+ return passes && l.kind === "bars" ? { ...l, continues: passes } : l;
134
+ });
135
+ return { lines: out, diagnostics };
136
+ }
@@ -32,12 +32,6 @@ export declare const MAX_EXPANDED_BARS = 10000;
32
32
  export declare const workFor: (share: number) => number;
33
33
  /** Every played bar in order, with an open repeat's pass included once. */
34
34
  export declare function flattenBars(events: ChartEvent[]): PlayedBar[];
35
- /**
36
- * Turn the written chart into the bars in play order: sections and their
37
- * replays, repeats, directive changes, `%` and elision. Its bars count
38
- * `written` from 1, a pickup included; `parseChart` and `extractPart`
39
- * renumber a pickup to 0 (grammar 2.4).
40
- */
41
35
  /**
42
36
  * `label` names the part a projected chart is (grammar 7.4), for its
43
37
  * messages; `share` is how many parts split the expansion budget.
@@ -115,6 +115,8 @@ function removeLastBar(events) {
115
115
  * `written` from 1, a pickup included; `parseChart` and `extractPart`
116
116
  * renumber a pickup to 0 (grammar 2.4).
117
117
  */
118
+ /** The lines of a repeat's ending for `pass` (grammar 5.1), or none. */
119
+ const endingOn = (it, pass) => it.endings.find((x) => x.passes.includes(pass))?.entries ?? [];
118
120
  /**
119
121
  * `label` names the part a projected chart is (grammar 7.4), for its
120
122
  * messages; `share` is how many parts split the expansion budget.
@@ -505,9 +507,8 @@ sing) {
505
507
  where.pass = phase === "main" ? pass : 1;
506
508
  for (const e of it.entries)
507
509
  playLine(e, out);
508
- const ending = it.endings.find((x) => x.passes.includes(pass));
509
- if (ending)
510
- playLine(ending.entry, out);
510
+ for (const e of endingOn(it, pass))
511
+ playLine(e, out);
511
512
  }
512
513
  Object.assign(where, { pass: outer.pass, passes: outer.passes });
513
514
  };
@@ -12,7 +12,7 @@ export { extractPart, parseChart } from "./parse.js";
12
12
  export { projectPart } from "./parts.js";
13
13
  export { pedalStates } from "./pedal.js";
14
14
  export { opensWithPickup } from "./pickup.js";
15
- export { printCell, printChart, printLine, printParsed, printPart, printPasses, printSlot, reduceSlots, } from "./print.js";
15
+ export { printCell, printChart, printedAsWritten, printLine, printParsed, printPart, printPasses, printSlot, reduceSlots, unreadSlots, } from "./print.js";
16
16
  export { memberShares } from "./shares.js";
17
17
  export { streamKey } from "./systems.js";
18
18
  export { type TransposeBy, transposeChart } from "./transpose.js";
@@ -12,7 +12,7 @@ export { extractPart, parseChart } from "./parse.js";
12
12
  export { projectPart } from "./parts.js";
13
13
  export { pedalStates } from "./pedal.js";
14
14
  export { opensWithPickup } from "./pickup.js";
15
- export { printCell, printChart, printLine, printParsed, printPart, printPasses, printSlot, reduceSlots, } from "./print.js";
15
+ export { printCell, printChart, printedAsWritten, printLine, printParsed, printPart, printPasses, printSlot, reduceSlots, unreadSlots, } from "./print.js";
16
16
  export { memberShares } from "./shares.js";
17
17
  export { streamKey } from "./systems.js";
18
18
  export { transposeChart } from "./transpose.js";
@@ -7,7 +7,8 @@ const slotsOf = (l) => l.cells.flatMap((c) => (c.kind === "slots" ? c.slots.flat
7
7
  function notesOnlyProblem(l) {
8
8
  const slots = slotsOf(l);
9
9
  const harmony = slots.some((s) => s.kind === "nc" ||
10
- s.kind === "unknown" ||
10
+ // An unreadable slot is already an error of its own, not harmony written here.
11
+ (s.kind === "unknown" && s.text === undefined) ||
11
12
  (s.kind === "chord" && (s.chord.kind !== "notes" || s.voicing !== undefined)));
12
13
  if (harmony)
13
14
  return "chord symbols go on the part's first line; write a note set here, or a voicing on the first line";
@@ -1,4 +1,4 @@
1
- import type { Cell, ChartParse, Line, Slot } from "./types.js";
1
+ import type { Cell, ChartParse, Line, SimpleSlot, Slot } from "./types.js";
2
2
  /**
3
3
  * The fewest slots with the same timeline: `G / D /` is `G D`, `-- --` is `--`.
4
4
  * Only a slot with no attack of its own merges (`/`, a repeated `--` or
@@ -30,6 +30,16 @@ export declare function printChart(text: string): string;
30
30
  * text isn't read twice. `edit`, if given, changes each line before it prints.
31
31
  */
32
32
  export declare function printParsed(text: string, parsed: ChartParse, edit?: (l: Line) => Line): string;
33
+ /** The unreadable slots of a bar line, or of any cells (grammar 2.3): unknown harmony that keeps its text. */
34
+ export declare const unreadSlots: (l: {
35
+ cells: Cell[];
36
+ }) => SimpleSlot[];
37
+ /**
38
+ * The lines that print as written (spec §8): every line with an error,
39
+ * except a bar line whose only errors are its unreadable slots, one each,
40
+ * which prints in canonical form with each slot's text as written.
41
+ */
42
+ export declare function printedAsWritten(parsed: ChartParse): Set<number>;
33
43
  /**
34
44
  * One part of a chart in canonical form, as a single-part chart (grammar
35
45
  * 7.4): its `part:` line, the tutti lines, its own lines, and `N.C.` bars
@@ -1,9 +1,10 @@
1
- import { isBar } from "./barLine.js";
1
+ import { isBar, simpleSlots } from "./barLine.js";
2
2
  import { printDirection } from "./direction.js";
3
3
  import { beatsOf } from "./directives.js";
4
4
  import { readDocument } from "./document.js";
5
5
  import { printKey } from "./keys.js";
6
6
  import { extractPart, parseChart } from "./parse.js";
7
+ import { splitSyllable } from "./syllable.js";
7
8
  /** A slot with no attack of its own continues whatever sounds before it. A repeated chord name is a re-attack. */
8
9
  function continues(sounding, s) {
9
10
  if (s.kind === "hold")
@@ -62,7 +63,16 @@ const printLyricSlot = (s) => {
62
63
  return printSyllable(s.syllable);
63
64
  return s.kind === "hold" ? "/" : "--";
64
65
  };
66
+ /** An unreadable slot as written: a dotted member's dot goes back before its syllable. */
67
+ function printUnread(text, dotted) {
68
+ if (!dotted)
69
+ return text;
70
+ const { note, syllable } = splitSyllable(text);
71
+ return `${note}.${syllable === null ? "" : `:${syllable}`}`;
72
+ }
65
73
  function printSimple(s) {
74
+ if (s.kind === "unknown" && s.text !== undefined)
75
+ return printUnread(s.text, Boolean(s.dotted));
66
76
  const body = s.kind === "chord" ? s.chord.canonical + (s.voicing?.canonical ?? "") : SYMBOLS[s.kind];
67
77
  const sung = s.kind === "chord" && s.syllable ? `:${printSyllable(s.syllable)}` : "";
68
78
  return printMarks(s) + body + (s.dotted ? "." : "") + sung;
@@ -386,8 +396,25 @@ function beatsOfLines(parsed) {
386
396
  export function printParsed(text, parsed, edit = (l) => l) {
387
397
  return printLines(text, parsed, edit, new Set());
388
398
  }
399
+ /** The unreadable slots of a bar line, or of any cells (grammar 2.3): unknown harmony that keeps its text. */
400
+ export const unreadSlots = (l) => simpleSlots(l.cells).filter((s) => s.kind === "unknown" && s.text !== undefined);
401
+ /**
402
+ * The lines that print as written (spec §8): every line with an error,
403
+ * except a bar line whose only errors are its unreadable slots, one each,
404
+ * which prints in canonical form with each slot's text as written.
405
+ */
406
+ export function printedAsWritten(parsed) {
407
+ const errors = new Map();
408
+ for (const d of parsed.diagnostics)
409
+ if (d.severity === "error")
410
+ errors.set(d.line, (errors.get(d.line) ?? 0) + 1);
411
+ for (const l of parsed.lines)
412
+ if (l.kind === "bars" && errors.get(l.line) === unreadSlots(l).length)
413
+ errors.delete(l.line);
414
+ return new Set(errors.keys());
415
+ }
389
416
  function linePrinter(parsed, edit) {
390
- const errored = new Set(parsed.diagnostics.filter((d) => d.severity === "error").map((d) => d.line));
417
+ const errored = printedAsWritten(parsed);
391
418
  const beatsFor = beatsOfLines(parsed);
392
419
  const systems = systemTexts(parsed, errored, beatsFor, edit);
393
420
  return (raw, l) => {
@@ -4,10 +4,10 @@ export type Entry = {
4
4
  line: Line;
5
5
  repeat: Repeat;
6
6
  };
7
- /** One ending: the passes it plays on and its bar line. */
7
+ /** One ending: the passes it plays on and its bar lines (grammar 5.1). */
8
8
  export type Ending = {
9
9
  passes: number[];
10
- entry: Entry;
10
+ entries: Entry[];
11
11
  };
12
12
  /** A line, or a `|: … :|` repeat; one with endings plays `repeat` passes, each taking its ending. */
13
13
  export type Item = ({
@@ -1,3 +1,4 @@
1
+ import { BETWEEN_ENDINGS } from "./endingLines.js";
1
2
  const passesToken = (b) => `|${(b.ending ?? []).join(",")}`;
2
3
  const asLine = (line) => ({ kind: "line", line, repeat: null });
3
4
  const highestPass = (endings) => Math.max(...endings.flatMap((b) => b.ending ?? []));
@@ -16,40 +17,44 @@ function passProblems(endings, last) {
16
17
  problems.push([last, `the last ending must be the one for pass ${highest}`]);
17
18
  return problems;
18
19
  }
19
- /** Every ending but the last goes back with `:|`; the last plays on. */
20
+ /** Every ending but the last goes back with `:|` on its last line; the last plays on. */
20
21
  function closeProblems(endings, last) {
21
- return endings.flatMap((b) => {
22
+ return endings.flatMap(({ head: b, lines }) => {
23
+ const closes = lines.at(-1)?.closes ?? false;
22
24
  if (b === last)
23
- return b.closes ? [[b, "the last ending plays on, so it doesn't close with :|"]] : [];
24
- return b.closes ? [] : [[b, "an ending before the last goes back with :|"]];
25
+ return closes ? [[b, "the last ending plays on, so it doesn't close with :|"]] : [];
26
+ return closes ? [] : [[b, "an ending before the last goes back with :|"]];
25
27
  });
26
28
  }
27
29
  /** A repeat with its endings, or, if they have problems, each line played once. */
28
30
  function closeEndings(e, error) {
29
- const last = e.endings.at(-1);
31
+ const heads = e.endings.map((x) => x.head);
32
+ const last = heads.at(-1);
30
33
  if (!last)
31
34
  return [];
32
- const problems = [...passProblems(e.endings, last), ...closeProblems(e.endings, last)];
35
+ const problems = [...passProblems(heads, last), ...closeProblems(e.endings, last)];
33
36
  for (const [b, message] of problems)
34
37
  error(b.line, message, passesToken(b));
35
38
  const between = e.between.map((x) => asLine(x.line));
39
+ const written = e.endings.flatMap((x) => x.lines);
36
40
  if (problems.length)
37
- return [...e.entries.map((x) => asLine(x.line)), ...e.endings.map(asLine), ...between];
38
- const endings = e.endings.map((b) => ({
39
- passes: b.ending ?? [],
40
- entry: { line: b, repeat: null },
41
+ return [...e.entries.map((x) => asLine(x.line)), ...written.map(asLine), ...between];
42
+ const endings = e.endings.map((x) => ({
43
+ passes: x.head.ending ?? [],
44
+ entries: x.lines.map((line) => ({ line, repeat: null })),
41
45
  }));
42
- const repeat = highestPass(e.endings);
46
+ const repeat = highestPass(heads);
43
47
  return [{ kind: "bracket", line: e.line, entries: e.entries, repeat, endings }, ...between];
44
48
  }
45
49
  /** An ending line starts the endings of the open repeat, or continues them. */
46
50
  function takeEnding(st, bars, error) {
47
51
  if (bars.repeat !== null)
48
52
  error(bars.line, "x N on an ending: the endings give the count", passesToken(bars));
53
+ const ending = { head: bars, lines: [bars] };
49
54
  if (st.open)
50
- st.endings = { ...st.open, endings: [bars], between: [] };
55
+ st.endings = { ...st.open, endings: [ending], between: [] };
51
56
  else if (st.endings)
52
- st.endings.endings.push(bars);
57
+ st.endings.endings.push(ending);
53
58
  else {
54
59
  error(bars.line, "an ending follows the bars of a |: … :| repeat", passesToken(bars));
55
60
  st.items.push(asLine(bars));
@@ -91,8 +96,13 @@ function addEntry(st, entry) {
91
96
  else
92
97
  st.items.push({ kind: "line", ...entry });
93
98
  }
94
- /** Lines that may sit between endings (grammar 5.1): they mean nothing to the timeline. */
95
- const BETWEEN_ENDINGS = new Set(["text", "credit", "lyrics", "break"]);
99
+ const repeatToken = (r) => (r === "open" ? "x ..." : `x${r}`);
100
+ /** A line an ending continues onto (grammar 5.1) joins it; its own `x N` is an error, as on the ending's first line. */
101
+ function continueEnding(e, bars, error) {
102
+ if (bars.repeat !== null)
103
+ error(bars.line, "x N on an ending: the endings give the count", repeatToken(bars.repeat));
104
+ e.endings.at(-1)?.lines.push(bars);
105
+ }
96
106
  /**
97
107
  * Pair `|:` and `:|` within one section's lines, with the endings that
98
108
  * follow a repeat (grammar 5.1). Problems are reported, and what cannot
@@ -108,6 +118,8 @@ export function pairRepeats(lines, error) {
108
118
  for (const l of lines) {
109
119
  if (l.kind === "bars" && l.ending)
110
120
  takeEnding(st, l, error);
121
+ else if (l.kind === "bars" && l.continues && st.endings)
122
+ continueEnding(st.endings, l, error);
111
123
  else if (st.endings && BETWEEN_ENDINGS.has(l.kind))
112
124
  st.endings.between.push({ line: l, repeat: null });
113
125
  else {
@@ -9,7 +9,9 @@ export type TransposeBy = {
9
9
  * The chart in another key, as canonical text (spec §8). Chord roots, slash
10
10
  * basses, note sets and every `key:` line move; text never does. Spelling
11
11
  * follows the interval from the chart's first key, so every chord keeps its
12
- * place in the key. Lines with errors stay as written, with a warning; a
12
+ * place in the key. A slot that can't be read stays as written, with a
13
+ * warning, and its line's other chords move; a line excluded for an error
14
+ * stays as written, with a warning; a
13
15
  * target that isn't a key, or a target key for a chart with none, returns
14
16
  * the text unchanged with an error. Never throws.
15
17
  */
@@ -5,7 +5,7 @@ import { printChord } from "../chords/print.js";
5
5
  import { parseDirectiveLine } from "./directives.js";
6
6
  import { alterOf, conventionalKey, plain, SHARPS, spellPitch } from "./keys.js";
7
7
  import { parseChart } from "./parse.js";
8
- import { printParsed } from "./print.js";
8
+ import { printedAsWritten, printParsed, unreadSlots } from "./print.js";
9
9
  const mod = (n, m) => ((n % m) + m) % m;
10
10
  /** The key `semitones` away, spelled with the fewest accidentals; sharps win a tie (F# over Gb). */
11
11
  function nearestKey(key, semitones) {
@@ -90,11 +90,23 @@ function moveLine(l, move, warn) {
90
90
  return { ...l, set: { ...l.set, key: { ...l.set.key, tonic: move.spell(l.set.key.tonic) } } };
91
91
  return l;
92
92
  }
93
+ /** A warning for an unreadable slot (grammar 2.3), which transposing leaves as written. */
94
+ const unmoved = (line, slot) => {
95
+ const token = slot.kind === "unknown" ? (slot.text ?? "?") : "";
96
+ return {
97
+ line,
98
+ severity: "warning",
99
+ message: `${token} can't move: it can't be read, so it stays as written`,
100
+ token,
101
+ };
102
+ };
93
103
  /**
94
104
  * The chart in another key, as canonical text (spec §8). Chord roots, slash
95
105
  * basses, note sets and every `key:` line move; text never does. Spelling
96
106
  * follows the interval from the chart's first key, so every chord keeps its
97
- * place in the key. Lines with errors stay as written, with a warning; a
107
+ * place in the key. A slot that can't be read stays as written, with a
108
+ * warning, and its line's other chords move; a line excluded for an error
109
+ * stays as written, with a warning; a
98
110
  * target that isn't a key, or a target key for a chart with none, returns
99
111
  * the text unchanged with an error. Never throws.
100
112
  */
@@ -106,13 +118,18 @@ export function transposeChart(text, by) {
106
118
  return { text, diagnostics: [move] };
107
119
  const physical = text.replace(/^/, "").split(/\r?\n/);
108
120
  const diagnostics = [];
109
- for (const line of new Set(parsed.diagnostics.filter((d) => d.severity === "error").map((d) => d.line)))
121
+ const asWritten = printedAsWritten(parsed);
122
+ for (const line of asWritten)
110
123
  diagnostics.push({
111
124
  line,
112
125
  severity: "warning",
113
126
  message: "not transposed: this line has an error",
114
127
  token: physical[line - 1]?.trim() ?? "",
115
128
  });
129
+ for (const l of parsed.lines)
130
+ if (l.kind === "bars" && !asWritten.has(l.line))
131
+ for (const s of unreadSlots(l))
132
+ diagnostics.push(unmoved(l.line, s));
116
133
  const warn = (line, token) => diagnostics.push({
117
134
  line,
118
135
  severity: "warning",
@@ -106,8 +106,14 @@ export type SimpleSlot = ({
106
106
  } | {
107
107
  kind: "silence";
108
108
  push?: Push;
109
- } | {
109
+ }
110
+ /**
111
+ * Unknown harmony: a written `?`, or a slot that can't be read (an error,
112
+ * grammar principle 4), which keeps the author's `text` as written.
113
+ */
114
+ | {
110
115
  kind: "unknown";
116
+ text?: string;
111
117
  }) & {
112
118
  /** A dotted member of a two-member group (grammar 2.2): three quarters of its slot. */
113
119
  dotted?: true;
@@ -199,6 +205,11 @@ export type Line = {
199
205
  repeat: Repeat;
200
206
  /** The passes an ending plays on (grammar 5.1), in order; null for any other bar line. */
201
207
  ending: number[] | null;
208
+ /**
209
+ * On a plain bar line that continues an ending onto another line
210
+ * (grammar 5.1): that ending's passes. Absent on every other line.
211
+ */
212
+ continues?: number[];
202
213
  /** The declared label of the part whose line this is (grammar 7.4); absent on a tutti line and in a single-part chart. */
203
214
  part?: string;
204
215
  /** The part's line this is (`RH` in `Pno.RH`, grammar 7.6), as first spelled; absent on a part's bare line. */
@@ -1,7 +1,7 @@
1
- import { isBar } from "./barLine.js";
1
+ import { isBar, simpleSlots as slotsIn } from "./barLine.js";
2
2
  import { perWritten, slotTimes } from "./shares.js";
3
3
  /** Each simple slot of a bar line's cells. */
4
- const simpleSlots = (l) => l.cells.flatMap((c) => c.kind === "slots" ? c.slots.flatMap((s) => (s.kind === "group" ? s.members : [s])) : []);
4
+ const simpleSlots = (l) => slotsIn(l.cells);
5
5
  const isNote = (s) => s.kind === "chord" && s.chord.kind === "notes";
6
6
  const hasSyllables = (l) => simpleSlots(l).some((s) => s.kind === "chord" && s.syllable);
7
7
  const hasNotes = (l) => simpleSlots(l).some(isNote);
@@ -1,6 +1,7 @@
1
1
  import { toHarte } from "./harte.js";
2
2
  import { noteSemitone, transpose } from "./intervals.js";
3
3
  import { canonicalParts, printChord } from "./print.js";
4
+ import { alteredFifth, bareScan, intoGroup, pullBare, separate, stackedWarning, } from "./stacked.js";
4
5
  import { ALIASES, chordIntervals, EXTENSIONS, isOmission, OMISSIONS, rejection, TONES, validateParts, } from "./vocabulary.js";
5
6
  const ROOT = /^[A-G][#b]?/;
6
7
  const INLINE_ALTERATION = /^(b5|#5|b9|#9|#11|b13)/;
@@ -71,6 +72,14 @@ function toneProblem(tone, before) {
71
72
  }
72
73
  return TONES.includes(tone) ? null : `"${tone}" is not a tone a parenthesis can add`;
73
74
  }
75
+ /** The parts a normalized symbol is spelled from, valid together, or why not. */
76
+ function readParts(text, symbol) {
77
+ const read = tokenize(text);
78
+ if (typeof read === "string")
79
+ return { message: `${symbol}: ${read}`, token: symbol };
80
+ const parts = powerChord(read);
81
+ return validateParts(parts, symbol) ?? parts;
82
+ }
74
83
  const ORDINAL = { 3: "3rd", 5: "5th" };
75
84
  /**
76
85
  * The intervals once `no3`/`no5` leave out a tone, or why they can't: the
@@ -113,14 +122,19 @@ function logicGroups(rest) {
113
122
  const others = tones.filter((t) => t !== "5");
114
123
  return `5${others.length ? `(${others.join(",")})` : ""}${joined.slice(group[0].length)}`;
115
124
  }
116
- /** Appendix A.5 and A.6: Unicode, rejections, then aliases into canonical vocabulary. */
117
- function normalizeSymbol(symbol) {
118
- const text = symbol.replace(/♯/g, "#").replace(/♭/g, "b");
125
+ const BARE_ADD = bareScan("add(?:2|4|9|11)");
126
+ /** The text a symbol is read from: ♯ and ♭ as # and b (Appendix A.5). */
127
+ const ascii = (symbol) => symbol.replace(/♯/g, "#").replace(/♭/g, "b");
128
+ /** Appendix A.5 and A.6: rejections, then aliases into canonical vocabulary. */
129
+ function normalizeSymbol(text) {
119
130
  const rejected = rejection(text, noteSemitone);
120
131
  if (rejected)
121
132
  return rejected;
122
133
  const root = ROOT.exec(text)?.[0] ?? "";
123
134
  let rest = text.slice(root.length);
135
+ // Stacked spellings first, on the name as written; the aliases then read what is left.
136
+ const separated = separate(rest);
137
+ rest = separated.text;
124
138
  for (const [pattern, replacement] of ALIASES)
125
139
  rest = rest.replace(pattern, replacement);
126
140
  rest = logicGroups(rest);
@@ -129,33 +143,42 @@ function normalizeSymbol(symbol) {
129
143
  // `(add9)` is `(9)`: inside a group, `add` before a tone it may add is dropped.
130
144
  rest = rest.replace(/(?<=[(,]\s*)add(2|4|9|11)(?=\s*[,)])/g, "$1");
131
145
  // A bare `add9` outside any group; what is left inside one is the tokenizer's to name.
132
- const bare = /add(2|4|9|11)(?![^(]*\))/g;
133
- const added = [...rest.matchAll(bare)].map((m) => m[1] ?? "");
134
- if (added.length) {
135
- rest = rest.replace(bare, "");
136
- const close = rest.indexOf(")");
137
- if (close >= 0)
138
- rest = `${rest.slice(0, close)},${added.join(",")}${rest.slice(close)}`;
139
- else {
140
- const slash = /\/[A-G][#b]?$/.exec(rest);
141
- const at = slash ? slash.index : rest.length;
142
- rest = `${rest.slice(0, at)}(${added.join(",")})${rest.slice(at)}`;
143
- }
144
- }
145
- return { text: root + rest };
146
+ const bare = pullBare(rest, BARE_ADD);
147
+ rest = intoGroup(bare.text, bare.taken.map((a) => a.slice(3)));
148
+ return { text: root + rest, separated };
149
+ }
150
+ /**
151
+ * The warning a stacked spelling reads with (grammar 3): its suggestion is
152
+ * the symbol with its items separated, or the canonical spelling when that
153
+ * would not read as the same chord.
154
+ */
155
+ function stacked(symbol, text, normal, canonical) {
156
+ const { runTogether, bareOmission } = normal.separated;
157
+ if (!runTogether && !bareOmission)
158
+ return null;
159
+ const root = ROOT.exec(text)?.[0] ?? "";
160
+ const written = root + separate(text.slice(root.length)).text;
161
+ const check = parseChord(written);
162
+ const same = check.ok && check.value.canonical === canonical;
163
+ return stackedWarning(symbol, normal.separated, same ? written : canonical);
146
164
  }
147
165
  export function parseChord(symbol) {
148
- const normal = normalizeSymbol(symbol);
166
+ const text = ascii(symbol);
167
+ const normal = normalizeSymbol(text);
149
168
  if (!("text" in normal))
150
169
  return { ok: false, error: normal };
151
- const read = tokenize(normal.text);
152
- if (typeof read === "string") {
153
- return { ok: false, error: { message: `${symbol}: ${read}`, token: symbol } };
170
+ const r = readChord(symbol, normal.text);
171
+ if (!r.ok) {
172
+ return { ok: false, error: alteredFifth(symbol, text, r.error, (s) => parseChord(s).ok) };
154
173
  }
155
- const parts = powerChord(read);
156
- const invalid = validateParts(parts, symbol);
157
- if (invalid)
158
- return { ok: false, error: invalid };
174
+ const warning = stacked(symbol, text, normal, r.value.canonical);
175
+ return warning ? { ...r, warnings: [warning, ...r.warnings] } : r;
176
+ }
177
+ /** The chord a normalized symbol names. */
178
+ function readChord(symbol, text) {
179
+ const parts = readParts(text, symbol);
180
+ if ("message" in parts)
181
+ return { ok: false, error: parts };
159
182
  const added = chordIntervals({ ...parts, tones: parts.tones.filter((t) => !isOmission(t)) }, symbol);
160
183
  const { warnings, alteredOpen } = added;
161
184
  const intervals = omit(added.intervals, parts, symbol);
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Stacked spellings (grammar 3, Appendix A.5): notation programs print a
3
+ * chord's alterations one after another with no separator ("D6 add9
4
+ * omit5"), so a chart arrives as `D6(omit5add9)` or `Gadd9omit3`. These
5
+ * read as their comma-separated form. Every scan here is one pass over the
6
+ * text, so a long symbol costs its length.
7
+ */
8
+ import type { Diagnostic } from "./types.js";
9
+ /** A scan for a whole group or a bare match of `bare`: one pass, never a lookahead per match. */
10
+ export declare const bareScan: (bare: string) => RegExp;
11
+ /**
12
+ * The text with every match of `scan`'s bare pattern outside a parenthesis
13
+ * taken out (and each group's items passed through `group`), and what was
14
+ * taken.
15
+ */
16
+ export declare function pullBare(rest: string, scan: RegExp, group?: (inner: string) => string): {
17
+ text: string;
18
+ taken: string[];
19
+ };
20
+ /** The text with `items` added to its last group, or in a new group before any slash bass. */
21
+ export declare function intoGroup(rest: string, items: string[]): string;
22
+ export type Separated = {
23
+ text: string;
24
+ runTogether: boolean;
25
+ bareOmission: boolean;
26
+ };
27
+ /**
28
+ * The text after a root with items run together in a parenthesis separated
29
+ * by commas, and a bare `omit`/`no` ending the chord's name (after the
30
+ * quality however it is spelled, before any parenthesis or slash bass)
31
+ * moved into the last group (or a new one): `6(omit5add9)` is `6(omit5,add9)`, `add9omit3` is
32
+ * `add9(omit3)`.
33
+ */
34
+ export declare function separate(rest: string): Separated;
35
+ /** The warning a stacked spelling reads with, suggesting `suggestion`; null when it isn't one. */
36
+ export declare function stackedWarning(symbol: string, separated: Separated, suggestion: string): Diagnostic | null;
37
+ /**
38
+ * The error for a symbol that can't be read, with a suggestion when it
39
+ * writes an altered fifth before the parenthesis on a chord with no
40
+ * extension (grammar 3 keeps `Ab5` the A♭ power chord). `reads` says
41
+ * whether a suggestion reads. Where the root's own accidental could be the
42
+ * fifth's (`Gb5(omit3)`), the message says it is ambiguous, with no
43
+ * suggestion; only when that fifth reading would itself read.
44
+ */
45
+ export declare function alteredFifth(symbol: string, text: string, error: Diagnostic, reads: (symbol: string) => boolean): Diagnostic;
@@ -0,0 +1,122 @@
1
+ /** The shape of one parenthesis item; the tokenizer judges what it names. */
2
+ const ITEM = /^(?:add\d+|(?:omit\s*|no)\d+|[b#]?\d+)$/;
3
+ /** Where an item run together with the one before it starts. */
4
+ const ITEM_START = /(?=add|omit|no|[b#])/;
5
+ /** A slash bass at the end of the text after the root. */
6
+ const BASS = /\/[A-G][#b]?$/;
7
+ /** Where the chord's name ends: its first parenthesis or slash bass. */
8
+ const NAME_END = /\(|\/[A-G]/;
9
+ /** The items run together in one parenthesis item, or the item alone when it isn't a run of valid items. */
10
+ function splitItem(item) {
11
+ const pieces = item.split(ITEM_START).map((p) => p.trim());
12
+ return pieces.length > 1 && pieces.every((p) => ITEM.test(p)) ? pieces : [item];
13
+ }
14
+ /** A scan for a whole group or a bare match of `bare`: one pass, never a lookahead per match. */
15
+ export const bareScan = (bare) => new RegExp(String.raw `\((?<inner>[^()]*)\)|${bare}`, "g");
16
+ /**
17
+ * The text with every match of `scan`'s bare pattern outside a parenthesis
18
+ * taken out (and each group's items passed through `group`), and what was
19
+ * taken.
20
+ */
21
+ export function pullBare(rest, scan, group = (inner) => inner) {
22
+ const taken = [];
23
+ const text = rest.replace(scan, (match, ...args) => {
24
+ const { inner } = args.at(-1);
25
+ if (inner !== undefined)
26
+ return `(${group(inner)})`;
27
+ taken.push(match);
28
+ return "";
29
+ });
30
+ return { text, taken };
31
+ }
32
+ /** The text with `items` added to its last group, or in a new group before any slash bass. */
33
+ export function intoGroup(rest, items) {
34
+ if (!items.length)
35
+ return rest;
36
+ const close = rest.lastIndexOf(")");
37
+ if (close >= 0)
38
+ return `${rest.slice(0, close)},${items.join(",")}${rest.slice(close)}`;
39
+ const at = BASS.exec(rest)?.index ?? rest.length;
40
+ return `${rest.slice(0, at)}(${items.join(",")})${rest.slice(at)}`;
41
+ }
42
+ /** A parenthesis and its items. */
43
+ const GROUP = /\((?<inner>[^()]*)\)/g;
44
+ /** A bare `omit`/`no` ending the chord's name. */
45
+ const TRAILING_OMISSION = /(?:omit\s*|no)\d+$/;
46
+ /**
47
+ * The text after a root with items run together in a parenthesis separated
48
+ * by commas, and a bare `omit`/`no` ending the chord's name (after the
49
+ * quality however it is spelled, before any parenthesis or slash bass)
50
+ * moved into the last group (or a new one): `6(omit5add9)` is `6(omit5,add9)`, `add9omit3` is
51
+ * `add9(omit3)`.
52
+ */
53
+ export function separate(rest) {
54
+ let runTogether = false;
55
+ const split = (inner) => {
56
+ const items = inner.split(",");
57
+ const out = items.flatMap(splitItem);
58
+ if (out.length > items.length)
59
+ runTogether = true;
60
+ return out.join(",");
61
+ };
62
+ const text = rest.replace(GROUP, (_, inner) => `(${split(inner)})`);
63
+ // The chord's name: what comes before the first parenthesis or slash bass
64
+ // (a slash before a letter; `6/9` is an extension), whatever follows it.
65
+ const end = NAME_END.exec(text)?.index ?? text.length;
66
+ const name = text.slice(0, end);
67
+ const bare = TRAILING_OMISSION.exec(name);
68
+ if (!bare)
69
+ return { text, runTogether, bareOmission: false };
70
+ const moved = intoGroup(name.slice(0, bare.index) + text.slice(end), [bare[0]]);
71
+ return { text: moved, runTogether, bareOmission: true };
72
+ }
73
+ /** The warning a stacked spelling reads with, suggesting `suggestion`; null when it isn't one. */
74
+ export function stackedWarning(symbol, separated, suggestion) {
75
+ const why = [
76
+ ...(separated.runTogether ? ["items in a parenthesis are separated by commas"] : []),
77
+ ...(separated.bareOmission ? ["an omission goes in parentheses"] : []),
78
+ ];
79
+ if (!why.length)
80
+ return null;
81
+ return { message: `${symbol}: ${why.join("; ")}`, token: symbol, suggestion };
82
+ }
83
+ /** An altered fifth straight after the root (and `m`), with no extension: `F#b5(omit3)`. */
84
+ const ALTERED_FIFTH = /^([A-G][#b]?)(m?)([b#]5)(?:\(([^()]*)\))?(\/[A-G][#b]?)?$/;
85
+ /** A root whose accidental a following `5` could be read with: `Gb5`, `G#5`. */
86
+ const SWALLOWED = /^([A-G])([#b])5(?:\(([^()]*)\))?(\/[A-G][#b]?)?$/;
87
+ /**
88
+ * The error for a symbol that can't be read, with a suggestion when it
89
+ * writes an altered fifth before the parenthesis on a chord with no
90
+ * extension (grammar 3 keeps `Ab5` the A♭ power chord). `reads` says
91
+ * whether a suggestion reads. Where the root's own accidental could be the
92
+ * fifth's (`Gb5(omit3)`), the message says it is ambiguous, with no
93
+ * suggestion; only when that fifth reading would itself read.
94
+ */
95
+ export function alteredFifth(symbol, text, error, reads) {
96
+ const s = SWALLOWED.exec(text);
97
+ if (s) {
98
+ const [, letter = "", accidental = "", inner, bass = ""] = s;
99
+ const items = inner?.trim() ? `,${inner}` : "";
100
+ const fifth = letter + separate(`(${accidental}5${items})${bass}`).text;
101
+ if (!reads(fifth))
102
+ return error;
103
+ const power = `${letter}${accidental}5`;
104
+ return {
105
+ ...error,
106
+ message: `${error.message}; ambiguous: ${power} is always the ${letter}${accidental} power chord (grammar 3); a ${letter} chord with a ${accidental}5 writes it in the parentheses`,
107
+ };
108
+ }
109
+ const m = ALTERED_FIFTH.exec(text);
110
+ if (!m)
111
+ return error;
112
+ const [, root = "", minor = "", fifth = "", inner, bass = ""] = m;
113
+ const items = inner?.trim() ? `,${inner}` : "";
114
+ const suggestion = root + separate(`${minor}(${fifth}${items})${bass}`).text;
115
+ if (!reads(suggestion))
116
+ return error;
117
+ return {
118
+ message: `${symbol}: an altered 5th goes in the parentheses unless it follows an extension (grammar 3)`,
119
+ token: symbol,
120
+ suggestion,
121
+ };
122
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barmark",
3
- "version": "0.22.0",
3
+ "version": "0.23.1",
4
4
  "description": "Markdown-inspired plain-text notation for chord charts: a parser, a canonical printer and Harte-label conversion.",
5
5
  "type": "module",
6
6
  "exports": {