barmark 0.20.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -9,6 +9,52 @@ Releases follow the process in [RELEASING.md](RELEASING.md).
9
9
 
10
10
  ## [Unreleased]
11
11
 
12
+ ## [0.21.0] - 2026-11-08
13
+
14
+ ### Added
15
+
16
+ - **`nameNotes(pitchClasses, bass, key)`** names a chord from the pitch
17
+ classes sounding over a bass, spelled for the key, or returns null when
18
+ none fits: the name grammar 4's linter may suggest for a note set, and
19
+ what `@barmark/midi`'s import will call. Every root is tried, with the
20
+ fifth supplied where it is missing. The fewest added tones wins, a
21
+ slash and a supplied fifth costing one each; ties go to triads, then
22
+ sevenths, sixths, sus, extended chords and added tones, then the root
23
+ in the bass, then `(9)`, `(11)`, `(13)` over `(2)`, `(4)`, `(6)`.
24
+ Suffixes no one writes are never suggested: a degree both plain and
25
+ altered (`b9` with `9`), `(7)` on a sixth chord, a tone on `dim` or
26
+ `dim7`, an altered tone on `5`, `6` or `6/9`. `{G B F}` over G is `G7`,
27
+ `{E G C}` over E is `C/E`, `Am7/C`'s notes are `C6`, `{G B F E}` is
28
+ `G7(13)`; two pitch classes name only a power chord (`E5`). The bass is
29
+ spelled by its interval from the root, or by pitch when that would
30
+ double (`E(#9)/G`); with no key, a black-key root takes the spelling
31
+ with fewer awkward notes (`Db`, `C#m`, `G#dim7`).
32
+ - **`time` on a played bar in a one-bar meter** (Kevin's decision,
33
+ 2026-11-08, grammar 2.4, A.7): the meter of the `time:` in force,
34
+ whose beat `tempo:` counts there, so a short or odd bar never changes
35
+ speed. In `time: 6/8, tempo: 60` a `[2/8]` pickup plays at 60 dotted
36
+ quarters a minute, not 60 eighths. Absent on any other bar, where
37
+ `meter` is the `time:` meter. No change to what any chart means
38
+ otherwise.
39
+
40
+ ### Fixed
41
+
42
+ - **`printChart` prints many lyric rows in linear time.** Deciding
43
+ whether a row lies just under its bar line scanned every line of the
44
+ chart for a heading in between, once a row: 100 verses under each of
45
+ 500 bar lines took 9 s to print. The headings are now found by halves;
46
+ the same chart prints in about a second, parse included.
47
+ - **A part's tacet stand-in for a `%` is as long as the bar it copies**
48
+ (grammar 7.4, 2.4). Where one part writes `| [2/8] G | % |` and another
49
+ has no line, the resting part's bar for the `%` was a bar of the
50
+ running meter (`| [2/8] N.C. | N.C. |` in 6/8), so an extracted part
51
+ and the score disagreed on the bar's length. It is now `[2/8] N.C.`,
52
+ across line breaks and after a tutti line too. A bar of several parts
53
+ also takes its `time` from the part its meter comes from, the first
54
+ that plays, so a `%` of a one-bar meter where the lead part rests no
55
+ longer loses it (it played at 30 quarter notes a minute in 6/8 at
56
+ `tempo: 60`, not 90).
57
+
12
58
  ## [0.20.0] - 2026-11-08
13
59
 
14
60
  ### Changed
@@ -610,7 +656,8 @@ The first working release: the reference parser and printer for the
610
656
 
611
657
  - **A placeholder package that holds the `barmark` name** while the spec and parser are written.
612
658
 
613
- [Unreleased]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.20.0...HEAD
659
+ [Unreleased]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.21.0...HEAD
660
+ [0.21.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.20.0...barmark-v0.21.0
614
661
  [0.20.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.19.1...barmark-v0.20.0
615
662
  [0.19.1]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.19.0...barmark-v0.19.1
616
663
  [0.19.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.18.0...barmark-v0.19.0
package/README.md CHANGED
@@ -41,6 +41,7 @@ import {
41
41
  extractPart,
42
42
  harteToBarmark,
43
43
  keyFromText,
44
+ nameNotes,
44
45
  parseChart,
45
46
  parseChord,
46
47
  printChart,
@@ -56,7 +57,7 @@ const chart = parseChart(text);
56
57
  chart.title; // "Example Song"
57
58
  chart.parts; // [{ label: "Gtr", name: "Electric Guitar 1" }] from part: Gtr = Electric Guitar 1, in score order
58
59
  chart.credits; // { composer: ["Kevin Peckham"], lyricist: [], arranger: [], copyright: [] } from composer: Kevin Peckham
59
- chart.bars; // every bar in play order: its number as written, slots, section, key, meter, tempo, feel (and swingPercent)
60
+ chart.bars; // every bar in play order: its number as written, slots, section, key, meter (and in a one-bar meter the time: meter, whose beat tempo counts), tempo, feel (and swingPercent)
60
61
  chart.sections; // each section as played, with its first and last bar
61
62
  chart.diagnostics; // errors and warnings, each with a line number
62
63
 
@@ -78,6 +79,7 @@ if (chord.ok) chord.value.pitches; // ["B", "D", "F", "A"]
78
79
  if (chord.ok) chord.value.harte; // "B:hdim7"
79
80
 
80
81
  harteToBarmark("A:sus4(b7,9)"); // "A9sus4"
82
+ nameNotes([7, 11, 2, 5], 11, null); // "G7/B": a chord symbol for sounding pitch classes (0 = C) over a bass, spelled for a key; null when none fits
81
83
  ```
82
84
 
83
85
  ### Several parts
@@ -261,15 +261,19 @@ sing) {
261
261
  if (plan)
262
262
  phase = NEXT[phase]?.[d.kind] ?? phase;
263
263
  };
264
- /** A bar as played now; its slot count is checked the first time a written bar plays. */
264
+ /** A written bar's slot count, checked the first time it plays. */
265
+ const checkSlots = (p, meter, line) => {
266
+ if (!p.own || checked.has(p))
267
+ return;
268
+ checked.add(p);
269
+ const warning = uneven(p.slots.length, meter, line);
270
+ if (warning)
271
+ diagnostics.push(warning);
272
+ };
273
+ /** A bar as played now; in a one-bar meter it also carries the `time:` in force (grammar 2.4). */
265
274
  const barOf = (p, line) => {
266
275
  const meter = p.meter ?? state.time;
267
- if (p.own && !checked.has(p)) {
268
- checked.add(p);
269
- const warning = uneven(p.slots.length, meter, line);
270
- if (warning)
271
- diagnostics.push(warning);
272
- }
276
+ checkSlots(p, meter, line);
273
277
  const { key, tempo, change: tempoChange, feel, swingPercent } = state;
274
278
  return {
275
279
  index: 0,
@@ -277,6 +281,7 @@ sing) {
277
281
  line,
278
282
  section: sectionName,
279
283
  meter,
284
+ ...(p.meter && { time: state.time }),
280
285
  key,
281
286
  tempo,
282
287
  tempoChange,
@@ -6,6 +6,8 @@ export declare const alterOf: (note: string) => number;
6
6
  export declare function plain(note: string): string;
7
7
  /** Sharps (positive) or flats (negative) in a key's signature. */
8
8
  export declare const signature: (tonic: string, mode: Mode) => number;
9
+ /** Whether a pitch class is one of the key's seven. */
10
+ export declare const inScale: (pitchClass: number, key: Key) => boolean;
9
11
  /** A pitch class spelled in a key (or, with no key, from transposeChart's table). */
10
12
  export declare function spellPitch(pitchClass: number, key: Key | null): string;
11
13
  /** The same key spelled with the fewest accidentals; a tie keeps the spelling given. */
@@ -56,6 +56,8 @@ const scaleOf = (mode) => {
56
56
  const root = MAJOR_SCALE[start] ?? 0;
57
57
  return MAJOR_SCALE.map((_, i) => mod((MAJOR_SCALE[(start + i) % 7] ?? 0) - root, 12));
58
58
  };
59
+ /** Whether a pitch class is one of the key's seven. */
60
+ export const inScale = (pitchClass, key) => scaleOf(key.mode).includes(mod(pitchClass - noteSemitone(key.tonic), 12));
59
61
  /** Notes outside the mode: the major-scale map (bII, bIII, #IV, bVI, bVII). */
60
62
  const OUTSIDE = {
61
63
  0: { degree: 1, alter: 0 },
@@ -25,14 +25,15 @@ const meterText = (b) => `${b.meter.n}/${b.meter.d}`;
25
25
  /** Every stream's words in a bar, in verse order, then score order (grammar 7.7). */
26
26
  const lyricsOf = (bars) => bars.flatMap((b) => b.lyrics ?? []).sort((a, b) => a.verse - b.verse);
27
27
  /**
28
- * One bar of every part: shared fields from the first, the meter from the
29
- * first that plays, the words of every stream that sings.
28
+ * One bar of every part: shared fields from the first, the meter and the
29
+ * `time:` meter (grammar 2.4) together from the first that plays, the
30
+ * words of every stream that sings.
30
31
  */
31
32
  function zipBar(bars, report) {
32
33
  const [first, ...rest] = bars;
33
34
  const lyrics = lyricsOf(bars);
34
35
  const playing = bars.filter((b) => !b.tacet);
35
- const meter = playing[0]?.meter ?? first.meter;
36
+ const lead = playing[0] ?? first;
36
37
  const meters = [...new Set(playing.map(meterText))];
37
38
  // A `%` copies its bar's one-bar meter, so parts can disagree: say so on every line that plays the bar.
38
39
  if (meters.length > 1)
@@ -43,10 +44,11 @@ function zipBar(bars, report) {
43
44
  message: `the parts disagree on this bar's meter (${meters.join(", ")})`,
44
45
  token: "|",
45
46
  });
46
- const { lyrics: _l, ...shared } = first;
47
+ const { lyrics: _l, time: _t, ...shared } = first;
47
48
  return {
48
49
  ...shared,
49
- meter,
50
+ meter: lead.meter,
51
+ ...(lead.time && { time: lead.time }),
50
52
  parts: [first, ...rest].map(partBar),
51
53
  ...(lyrics.length && { lyrics }),
52
54
  };
@@ -1,8 +1,43 @@
1
- /** A bar of `N.C.` where the part rests; the system's marks stay (grammar 7.4). */
2
- const standInCell = (c) => c.kind === "slots" || c.kind === "simile"
1
+ /** The stream a labelled line plays (its part, and its line's name), or null for a tutti line. */
2
+ const streamOf = (l) => l.part === undefined ? null : `${l.part}\u0000${l.lineName ?? ""}`.toLowerCase();
3
+ /** Each `%` on a line gets the meter of the bar before it; returns the meter of the line's last bar. */
4
+ function copyAlong(cells, before, out) {
5
+ let meter = before;
6
+ for (const c of cells) {
7
+ if (c.kind === "simile")
8
+ out.set(c, meter);
9
+ else if (c.kind === "slots")
10
+ meter = c.meter;
11
+ }
12
+ return meter;
13
+ }
14
+ /**
15
+ * What each `%` copies its meter from: the bar before it on its part's
16
+ * line (a part's line, or a tutti line, which every part plays), across
17
+ * line breaks, so a stand-in for it is a bar of the same length.
18
+ */
19
+ function copiedMeters(lines) {
20
+ const out = new Map();
21
+ const last = new Map();
22
+ let tutti = null;
23
+ for (const l of lines) {
24
+ if (l.kind !== "bars")
25
+ continue;
26
+ const key = streamOf(l);
27
+ if (key === null) {
28
+ tutti = copyAlong(l.cells, tutti, out);
29
+ last.clear();
30
+ }
31
+ else
32
+ last.set(key, copyAlong(l.cells, last.has(key) ? (last.get(key) ?? null) : tutti, out));
33
+ }
34
+ return out;
35
+ }
36
+ /** A bar of `N.C.` where the part rests, as long as the bar it stands for; the system's marks stay (grammar 7.4). */
37
+ const standInCell = (copied) => (c) => c.kind === "slots" || c.kind === "simile"
3
38
  ? {
4
39
  kind: "slots",
5
- meter: c.kind === "slots" ? c.meter : null,
40
+ meter: c.kind === "slots" ? c.meter : (copied.get(c) ?? null),
6
41
  slots: [{ kind: "nc" }],
7
42
  tacet: true,
8
43
  }
@@ -24,12 +59,12 @@ const referenceOf = (system) => system.find((l) => l.kind === "bars" && !l.dropp
24
59
  * part's own line when it has one that errs, so its error stays its own,
25
60
  * or else the reference line, which has none.
26
61
  */
27
- function standIn(system, at) {
62
+ function standIn(system, at, copied) {
28
63
  const ref = referenceOf(system);
29
64
  if (!ref)
30
65
  return unread(at);
31
66
  const { part: _p, system: _s, dropped: _d, ...rest } = ref;
32
- return { ...rest, line: at.line, cells: ref.cells.map(standInCell) };
67
+ return { ...rest, line: at.line, cells: ref.cells.map(standInCell(copied)) };
33
68
  }
34
69
  /** A part's own line, as a single-part chart writes it. */
35
70
  function unlabelled(l) {
@@ -49,7 +84,7 @@ const ownLine = (system, s) => system.find((m) => m.part?.toLowerCase() === s.ke
49
84
  ? s.first && !(m.kind === "bars" && m.dropped)
50
85
  : m.lineName.toLowerCase() === s.name.toLowerCase()));
51
86
  /** 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;
87
+ const restingTutti = (l, copied) => l.kind === "bars" ? { ...l, cells: l.cells.map(standInCell(copied)) } : l;
53
88
  const inSystem = (l) => (l.kind === "bars" || l.kind === "invalid") && l.system !== undefined;
54
89
  function systemsOf(lines) {
55
90
  const systems = new Map();
@@ -64,7 +99,7 @@ function projectLine(l, s, systems) {
64
99
  return l.label?.toLowerCase() === s.key ? l : null;
65
100
  if (inSystem(l))
66
101
  return projectSystemLine(l, s, systems.get(l.system) ?? []);
67
- return s.first ? l : restingTutti(l);
102
+ return s.first ? l : restingTutti(l, s.copied);
68
103
  }
69
104
  /** A system's line in one stream's chart: its own line, a stand-in where it rests, or nothing. */
70
105
  function projectSystemLine(l, s, system) {
@@ -72,7 +107,7 @@ function projectSystemLine(l, s, system) {
72
107
  if (own === l && plays(l))
73
108
  return unlabelled(l);
74
109
  const at = own ?? referenceOf(system) ?? system[0];
75
- return at === l ? standIn(system, l) : null;
110
+ return at === l ? standIn(system, l, s.copied) : null;
76
111
  }
77
112
  /**
78
113
  * One part of a multi-part chart as a single-part chart's lines (grammar
@@ -88,7 +123,12 @@ export function projectPart(lines, parts, label, lineName = null) {
88
123
  const key = label.toLowerCase();
89
124
  const part = parts.find((p) => p.label?.toLowerCase() === key);
90
125
  const first = part?.lines?.[0];
91
- const s = { key, name: lineName, first: lineName === null || lineName === first };
126
+ const s = {
127
+ key,
128
+ name: lineName,
129
+ first: lineName === null || lineName === first,
130
+ copied: copiedMeters(lines),
131
+ };
92
132
  const systems = systemsOf(lines);
93
133
  return lines.map((l) => projectLine(l, s, systems)).filter((l) => l !== null);
94
134
  }
@@ -96,6 +136,7 @@ export function projectPart(lines, parts, label, lineName = null) {
96
136
  export function projectPartLines(lines, label) {
97
137
  const key = label.toLowerCase();
98
138
  const systems = systemsOf(lines);
139
+ const copied = copiedMeters(lines);
99
140
  return lines
100
141
  .map((l) => {
101
142
  if (l.kind === "part")
@@ -107,7 +148,7 @@ export function projectPartLines(lines, label) {
107
148
  if (own.length)
108
149
  return own.includes(l) ? l : null;
109
150
  const at = referenceOf(system) ?? system[0];
110
- return at === l ? standIn(system, l) : null;
151
+ return at === l ? standIn(system, l, copied) : null;
111
152
  })
112
153
  .filter((l) => l !== null);
113
154
  }
@@ -252,12 +252,26 @@ function alignSystem(block, parsed, beatsFor, edit) {
252
252
  const bars = (system[0]?.cells ?? []).flatMap((c, i) => (isBar(c) ? [i] : []));
253
253
  return alignBlock(pieces, rows, bars, width);
254
254
  }
255
- /** A row lies just under its bars unless a heading comes between: under a replay heading it doesn't. */
256
- const isUnder = (r, lines) => {
255
+ /**
256
+ * Whether a row lies just under its bars: not when a heading comes
257
+ * between (under a replay heading it doesn't). `headings` are the
258
+ * headings' line numbers in order, searched by halves, so many rows
259
+ * print in linear time.
260
+ */
261
+ const isUnder = (r, headings) => {
257
262
  if (!r.covers.length)
258
263
  return false;
259
264
  const last = Math.max(...r.covers);
260
- return !lines.some((l) => l.kind === "section" && l.line > last && l.line < r.line);
265
+ let lo = 0;
266
+ let hi = headings.length;
267
+ while (lo < hi) {
268
+ const mid = (lo + hi) >> 1;
269
+ if ((headings[mid] ?? 0) <= last)
270
+ lo = mid + 1;
271
+ else
272
+ hi = mid;
273
+ }
274
+ return !((headings[lo] ?? Number.POSITIVE_INFINITY) < r.line);
261
275
  };
262
276
  /** The block a bar line is in: its system's, or its own. */
263
277
  const blockKey = (l) => (l.kind === "bars" || l.kind === "invalid") && l.system !== undefined
@@ -275,8 +289,9 @@ function blocksOf(lines) {
275
289
  for (const l of lines.filter(inSystem))
276
290
  blockFor(blocks, l).lines.push(l);
277
291
  const byLine = new Map(lines.map((l) => [l.line, l]));
292
+ const headings = lines.flatMap((l) => (l.kind === "section" ? [l.line] : []));
278
293
  for (const r of lines) {
279
- if (r.kind !== "lyrics" || !isUnder(r, lines))
294
+ if (r.kind !== "lyrics" || !isUnder(r, headings))
280
295
  continue;
281
296
  // An extracted part keeps only some of a system's lines.
282
297
  const first = r.covers.map((n) => byLine.get(n)).find((l) => l !== undefined);
@@ -267,6 +267,13 @@ export type PlayedBar = {
267
267
  /** Heading text of the section occurrence, as written. */
268
268
  section: string | null;
269
269
  meter: Meter;
270
+ /**
271
+ * The `time:` meter in force, present only when a one-bar meter gives
272
+ * this bar its own, a `%` copying a bracketed bar included (grammar
273
+ * 2.4): `tempo:` counts its beat, not the bar's, so a short or odd bar
274
+ * never changes speed.
275
+ */
276
+ time?: Meter;
270
277
  key: Key | null;
271
278
  /** The steady tempo: where a change starts from, and what `a tempo` returns to. */
272
279
  tempo: number | null;
@@ -1,4 +1,5 @@
1
1
  export { harteToBarmark, parseHarte, toHarte } from "./harte.js";
2
+ export { nameNotes } from "./name.js";
2
3
  export { parseNoteSet } from "./noteSet.js";
3
4
  export { parseChord } from "./parse.js";
4
5
  export { printChord } from "./print.js";
@@ -1,4 +1,5 @@
1
1
  export { harteToBarmark, parseHarte, toHarte } from "./harte.js";
2
+ export { nameNotes } from "./name.js";
2
3
  export { parseNoteSet } from "./noteSet.js";
3
4
  export { parseChord } from "./parse.js";
4
5
  export { printChord } from "./print.js";
@@ -0,0 +1,8 @@
1
+ import type { Key } from "../chart/types.js";
2
+ /**
3
+ * A chord symbol for sounding pitch classes over a bass, spelled for the key;
4
+ * null when none fits (spec 5.6). Pitch classes are taken mod 12 and
5
+ * deduplicated; the bass is added when missing. Two pitch classes name only a
6
+ * power chord. The suggestion grammar 4's linter may make for a note set.
7
+ */
8
+ export declare function nameNotes(pitchClasses: number[], bass: number, key: Key | null): string | null;
@@ -0,0 +1,177 @@
1
+ import { inScale, spellPitch } from "../chart/keys.js";
2
+ import { noteSemitone, transpose } from "./intervals.js";
3
+ import { enumerateSuffixes, intervalSetKey } from "./suffixes.js";
4
+ const mod12 = (n) => ((n % 12) + 12) % 12;
5
+ const iv = (degree, alter = 0) => ({ degree, alter });
6
+ /** Each semitone count above a root, every way the vocabulary spells it. */
7
+ const SPELLINGS = [
8
+ [iv(1)],
9
+ [iv(9, -1)],
10
+ [iv(9)],
11
+ [iv(3, -1), iv(9, 1)],
12
+ [iv(3)],
13
+ [iv(11)],
14
+ [iv(5, -1), iv(11, 1)],
15
+ [iv(5)],
16
+ [iv(5, 1), iv(13, -1)],
17
+ [iv(13), iv(7, -2)],
18
+ [iv(7, -1)],
19
+ [iv(7)],
20
+ ];
21
+ /** Every spelling of a set of semitone counts above a root. */
22
+ function spellings(offsets) {
23
+ let out = [[]];
24
+ for (const o of offsets)
25
+ out = out.flatMap((s) => (SPELLINGS[o] ?? []).map((i) => [...s, i]));
26
+ return out;
27
+ }
28
+ /** Every suffix naming these semitone counts above a root, clusters left out. */
29
+ function named(offsets) {
30
+ const table = enumerateSuffixes();
31
+ return spellings(offsets).flatMap((intervals) => (table.get(intervalSetKey(intervals)) ?? []).filter((suffix) => !clashes(suffix)));
32
+ }
33
+ /** Every suffix naming the notes from each sounding root, with the fifth supplied where it is missing. */
34
+ function candidates(set) {
35
+ return set.flatMap((root) => {
36
+ const offsets = set.map((p) => mod12(p - root));
37
+ const found = named(offsets).map((suffix) => ({ root, suffix, supplied: false }));
38
+ if (set.length < 3 || offsets.includes(7))
39
+ return found;
40
+ return [
41
+ ...found,
42
+ ...named([...offsets, 7]).map((suffix) => ({ root, suffix, supplied: true })),
43
+ ];
44
+ });
45
+ }
46
+ /**
47
+ * Suffixes the table spells but no one writes: a degree held both plain and
48
+ * altered (`b9` with `9`, `b7` with `7`), a `(7)` on a sixth chord, any tone
49
+ * on `dim` or `dim7`, an altered tone on `5`, `6` or `6/9`.
50
+ */
51
+ function clashes(suffix) {
52
+ return degreeClash(suffix) || unwritten(suffix);
53
+ }
54
+ function degreeClash({ intervals }) {
55
+ const plain = new Set(intervals.filter((i) => i.alter === 0).map((i) => (i.degree - 1) % 7));
56
+ return intervals.some((i) => i.alter !== 0 && plain.has((i.degree - 1) % 7));
57
+ }
58
+ const altered = (tone) => /[#b]/.test(tone);
59
+ function unwritten({ parts }) {
60
+ const sixth = parts.extension === "6" || parts.extension === "6/9";
61
+ if (parts.quality === "dim")
62
+ return parts.tones.length > 0;
63
+ if (sixth && parts.tones.includes("7"))
64
+ return true;
65
+ return (sixth || parts.quality === "5") && parts.tones.some(altered);
66
+ }
67
+ /** Tones in parentheses, the half-diminished `m7(b5)`'s b5 not counted. */
68
+ function addedTones({ parts }) {
69
+ const halfDiminished = parts.quality === "m" && parts.extension === "7";
70
+ return parts.tones.filter((t) => !(halfDiminished && t === "b5")).length;
71
+ }
72
+ /** Triads, sevenths, sixths, sus, extended chords, then added tones. */
73
+ function family(suffix) {
74
+ const { extension, sus } = suffix.parts;
75
+ if (addedTones(suffix) > 0)
76
+ return 5;
77
+ if (sus)
78
+ return 3;
79
+ if (extension === null)
80
+ return 0;
81
+ if (extension === "7" || extension === "maj7")
82
+ return 1;
83
+ if (extension === "6" || extension === "6/9")
84
+ return 2;
85
+ return 4;
86
+ }
87
+ /** A tone the plain-tone tie-break puts last: `(2)`, `(4)`, `(6)` lose to `(9)`, `(11)`, `(13)`. */
88
+ const PLAIN_TONES = ["2", "4", "6"];
89
+ /**
90
+ * The order spec 5.6 ranks candidates by: cost (added tones, a slash, a
91
+ * supplied fifth), then family, root in the bass, plain tones, the shorter
92
+ * suffix and the root nearest above the bass.
93
+ */
94
+ function order(c, bass) {
95
+ const slash = c.root === bass ? 0 : 1;
96
+ const cost = addedTones(c.suffix) + slash + (c.supplied ? 1 : 0);
97
+ const plainTone = c.suffix.parts.tones.some((t) => PLAIN_TONES.includes(t)) ? 1 : 0;
98
+ return [cost, family(c.suffix), slash, plainTone, c.suffix.suffix.length, mod12(c.root - bass)];
99
+ }
100
+ function before(a, b) {
101
+ for (let i = 0; i < a.length; i++) {
102
+ const d = (a[i] ?? 0) - (b[i] ?? 0);
103
+ if (d !== 0)
104
+ return d < 0;
105
+ }
106
+ return false;
107
+ }
108
+ function cheapest(found, bass) {
109
+ let best = null;
110
+ for (const c of found) {
111
+ const rank = order(c, bass);
112
+ if (!best || before(rank, best.rank))
113
+ best = { c, rank };
114
+ }
115
+ return best?.c ?? null;
116
+ }
117
+ const doubled = (note) => /##|bb/.test(note);
118
+ /** A double accidental, or an E#, B#, Cb or Fb the key would not write itself. */
119
+ const faulty = (note, key) => doubled(note) || (/^(?:E#|B#|Cb|Fb)$/.test(note) && spellPitch(noteSemitone(note), key) !== note);
120
+ /** The bass by its interval from the root; by pitch when that spelling is faulty. */
121
+ function bassName(c, root, bass, s) {
122
+ const interval = c.suffix.intervals.find((i) => noteSemitone(transpose("C", i)) === mod12(bass - c.root));
123
+ const spelled = interval && transpose(root, interval);
124
+ if (!spelled || doubled(spelled) || (!s.trusted && faulty(spelled, s.key)))
125
+ return spellPitch(bass, s.key);
126
+ return spelled;
127
+ }
128
+ function write(c, root, bass, s) {
129
+ const slash = c.root === bass ? "" : `/${bassName(c, root, bass, s)}`;
130
+ return `${root}${c.suffix.suffix}${slash}`;
131
+ }
132
+ /** Faulty spellings among the root, its third and the bass. */
133
+ function faults(c, root, bass, s) {
134
+ const thirds = c.suffix.intervals.filter((i) => i.degree === 3).map((i) => transpose(root, i));
135
+ const notes = [root, ...thirds, ...(c.root === bass ? [] : [bassName(c, root, bass, s)])];
136
+ return notes.filter((n) => faulty(n, s.key)).length;
137
+ }
138
+ const LETTERS = "CDEFGAB";
139
+ /** The pitch class's other spelling with at most one accidental: `Db` for `C#`, `Fb` for `E`. */
140
+ function enharmonic(pc, first) {
141
+ for (const letter of LETTERS) {
142
+ const alter = mod12(pc - noteSemitone(letter) + 6) - 6;
143
+ const name = `${letter}${alter < 0 ? "b" : alter > 0 ? "#" : ""}`;
144
+ if (Math.abs(alter) <= 1 && name !== first)
145
+ return name;
146
+ }
147
+ return undefined;
148
+ }
149
+ /**
150
+ * The root by `spellPitch`; a root with no key or outside the key's scale takes
151
+ * its enharmonic spelling when that has fewer faults.
152
+ */
153
+ function spell(c, bass, key) {
154
+ const s = { key, trusted: key !== null && inScale(c.root, key) };
155
+ const first = spellPitch(c.root, key);
156
+ const other = s.trusted ? undefined : enharmonic(c.root, first);
157
+ if (other !== undefined && faults(c, other, bass, s) < faults(c, first, bass, s))
158
+ return write(c, other, bass, s);
159
+ return write(c, first, bass, s);
160
+ }
161
+ /**
162
+ * A chord symbol for sounding pitch classes over a bass, spelled for the key;
163
+ * null when none fits (spec 5.6). Pitch classes are taken mod 12 and
164
+ * deduplicated; the bass is added when missing. Two pitch classes name only a
165
+ * power chord. The suggestion grammar 4's linter may make for a note set.
166
+ */
167
+ export function nameNotes(pitchClasses, bass, key) {
168
+ const b = mod12(bass);
169
+ const set = [...new Set([...pitchClasses.map(mod12), b])];
170
+ if (set.length < 2)
171
+ return null;
172
+ let found = candidates(set);
173
+ if (set.length === 2)
174
+ found = found.filter((c) => c.suffix.suffix === "5");
175
+ const best = cheapest(found, b);
176
+ return best && spell(best, b, key);
177
+ }
@@ -1,8 +1,10 @@
1
1
  import type { Interval } from "./types.js";
2
+ import { type ChordParts } from "./vocabulary.js";
2
3
  export type Suffix = {
3
4
  suffix: string;
4
5
  intervals: Interval[];
5
6
  tones: number;
7
+ parts: ChordParts;
6
8
  };
7
9
  /**
8
10
  * Every chord suffix Appendix A allows (with up to three parenthesized tones),
@@ -34,7 +34,7 @@ export function enumerateSuffixes() {
34
34
  continue;
35
35
  const key = intervalSetKey(intervals);
36
36
  const list = found.get(key) ?? [];
37
- list.push({ suffix: printSuffix(parts), intervals, tones: tones.length });
37
+ list.push({ suffix: printSuffix(parts), intervals, tones: tones.length, parts });
38
38
  found.set(key, list);
39
39
  }
40
40
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barmark",
3
- "version": "0.20.0",
3
+ "version": "0.21.0",
4
4
  "description": "Markdown-inspired plain-text notation for chord charts: a parser, a canonical printer and Harte-label conversion.",
5
5
  "type": "module",
6
6
  "exports": {