barmark 0.17.1 → 0.19.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,39 @@ Releases follow the process in [RELEASING.md](RELEASING.md).
9
9
 
10
10
  ## [Unreleased]
11
11
 
12
+ ## [0.19.0] - 2026-11-07
13
+
14
+ ### Added
15
+
16
+ - **`keyFromText`, `conventionalKey`, `printKey` and `spellPitch`.** Read a key
17
+ as people and detectors write it (`F♯ minor`, `Bb Maj`), spell it with the
18
+ fewest accidentals, print it as `key:` does, and spell any pitch class in a
19
+ key.
20
+
21
+ ### Technical
22
+
23
+ - `transposeChart`'s keyless spelling and its key-signature helpers now live in
24
+ `src/chart/keys.ts`, shared with `spellPitch`; behaviour is unchanged.
25
+
26
+ ## [0.18.0] - 2026-11-07
27
+
28
+ ### Fixed
29
+
30
+ - **A cell of many quoted words parses in linear time.** Each word
31
+ re-read the whole cell and re-split what came before it, so 20,000
32
+ words in one bar took about 25 seconds; `barmark check` on a hostile
33
+ chart, and the MusicXML import's check of what it wrote, waited on it.
34
+ - **A text line starting `constructor:` or `__proto__:` gets no near-miss
35
+ warning.** The directive and credit near misses were looked up on plain
36
+ objects, so those words found `Object.prototype` and suggested
37
+ "function Object() { [native code] }:".
38
+
39
+ ### Changed
40
+
41
+ - **`title: X` warns as a near miss, suggesting `# X`** (Kevin's ruling,
42
+ 2026-11-07, issue #173), as `meter:` suggests `time:`. A chart's title
43
+ is its `#` line; the `title:` line stays text and prints as written.
44
+
12
45
  ## [0.17.1] - 2026-11-07
13
46
 
14
47
  A parse is plain data that owns its objects, and the README says what it
@@ -546,7 +579,9 @@ The first working release: the reference parser and printer for the
546
579
 
547
580
  - **A placeholder package that holds the `barmark` name** while the spec and parser are written.
548
581
 
549
- [Unreleased]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.17.1...HEAD
582
+ [Unreleased]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.19.0...HEAD
583
+ [0.19.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.18.0...barmark-v0.19.0
584
+ [0.18.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.17.1...barmark-v0.18.0
550
585
  [0.17.1]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.17.0...barmark-v0.17.1
551
586
  [0.17.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.16.0...barmark-v0.17.0
552
587
  [0.16.0]: https://github.com/kevinpeckham/barmark/compare/barmark-v0.15.0...barmark-v0.16.0
package/README.md CHANGED
@@ -36,15 +36,19 @@ declarations included and no runtime dependencies.
36
36
 
37
37
  ```ts
38
38
  import {
39
+ conventionalKey,
39
40
  degreeOf,
40
41
  extractPart,
41
42
  harteToBarmark,
43
+ keyFromText,
42
44
  parseChart,
43
45
  parseChord,
44
46
  printChart,
47
+ printKey,
45
48
  printParsed,
46
49
  printPart,
47
50
  projectPart,
51
+ spellPitch,
48
52
  transposeChart,
49
53
  } from "barmark";
50
54
 
@@ -62,6 +66,11 @@ printParsed(text, chart); // the same, from a parse you already have
62
66
  transposeChart("key: D\n| D | A | Bm | G |", { to: "Eb" }).text; // "key: Eb\n| Eb | Bb | Cm | Ab |\n"
63
67
  transposeChart(text, { semitones: -2 }); // { text, diagnostics }
64
68
 
69
+ keyFromText("F♯ minor"); // { tonic: "F#", mode: "minor" }; null when it isn't a key
70
+ conventionalKey({ tonic: "Ab", mode: "minor" }); // { tonic: "G#", mode: "minor" }: the spelling with fewest accidentals
71
+ printKey({ tonic: "F#", mode: "minor" }); // "F#m", as `key:` writes it
72
+ spellPitch(10, { tonic: "D", mode: "major" }); // "Bb": a pitch class (0 = C) spelled in a key; null key uses C C# D Eb ...
73
+
65
74
  degreeOf("C", { tonic: "D", mode: "major" }); // { degree: 7, alter: -1 }: C is b7 in D
66
75
 
67
76
  const chord = parseChord("Bm7(b5)");
@@ -212,32 +212,58 @@ const outsideSyllables = (cell) => {
212
212
  */
213
213
  function readWords(cell) {
214
214
  const words = [];
215
- let bare = "";
215
+ const chars = [...cell];
216
+ const sung = inSyllables(chars);
217
+ const bare = tokenCounter();
216
218
  let open = null;
217
- const sung = inSyllables([...cell]);
218
- for (const [i, ch] of [...cell].entries()) {
219
+ for (const [i, ch] of chars.entries()) {
219
220
  if (!QUOTES.has(ch) || (sung[i] && open === null)) {
220
221
  if (open === null)
221
- bare += ch;
222
+ bare.add(ch);
222
223
  continue;
223
224
  }
224
225
  if (open === null) {
225
226
  open = i;
226
227
  continue;
227
228
  }
228
- const text = [...cell]
229
+ const text = chars
229
230
  .slice(open + 1, i)
230
231
  .join("")
231
232
  .trim();
232
233
  if (!text)
233
234
  return { problem: "empty words between quotes", token: '""' };
234
- words.push({ text, at: tokens(bare).length });
235
- bare += " ";
235
+ words.push({ text, at: bare.count() });
236
+ bare.add(" ");
236
237
  open = null;
237
238
  }
238
239
  if (open !== null)
239
- return { problem: "words need a closing quote", token: [...cell].slice(open).join("") };
240
- return { bare, words };
240
+ return { problem: "words need a closing quote", token: chars.slice(open).join("") };
241
+ return { bare: bare.text(), words };
242
+ }
243
+ /** Text built a character at a time that knows how many `tokens` it holds, without splitting it again. */
244
+ function tokenCounter() {
245
+ const parts = [];
246
+ let done = 0;
247
+ let current = false;
248
+ let depth = 0;
249
+ return {
250
+ add(ch) {
251
+ parts.push(ch);
252
+ if (ch === "{")
253
+ depth++;
254
+ if (ch === "}")
255
+ depth = Math.max(0, depth - 1);
256
+ if (/\s/.test(ch) && depth === 0) {
257
+ if (current)
258
+ done++;
259
+ current = false;
260
+ }
261
+ else
262
+ current = true;
263
+ },
264
+ count: () => done + (current ? 1 : 0),
265
+ text: () => parts.join(""),
266
+ };
241
267
  }
242
268
  /** A leading `[n/d]` and the rest of the cell; `bad` is a bracket that is no time signature. */
243
269
  function readMeter(cell) {
@@ -45,7 +45,9 @@ export function nearCredit(text, line) {
45
45
  if (LYRIC_ROW.test(text))
46
46
  return null;
47
47
  const m = /^([^\s:]+)\s*:\s*(.*)$/.exec(text);
48
- const role = m?.[1] ? NEAR_CREDITS[m[1].toLowerCase()] : undefined;
48
+ const word = m?.[1]?.toLowerCase() ?? "";
49
+ // Own keys only: `constructor:` is not a credit's near miss.
50
+ const role = Object.hasOwn(NEAR_CREDITS, word) ? NEAR_CREDITS[word] : undefined;
49
51
  if (!m || !role)
50
52
  return null;
51
53
  return {
@@ -1,17 +1,7 @@
1
+ import { MODES } from "./keys.js";
1
2
  export const DIRECTIVE_NAMES = ["key", "time", "tempo", "feel"];
2
3
  /** A directive written after a comma, in a line that runs to its end (`part:`, credits). */
3
4
  export const DIRECTIVE_AFTER = /,\s*(key|time|tempo|feel)\s*:/i;
4
- const MODES = [
5
- "major",
6
- "minor",
7
- "ionian",
8
- "dorian",
9
- "phrygian",
10
- "lydian",
11
- "mixolydian",
12
- "aeolian",
13
- "locrian",
14
- ];
15
5
  const FEELS = ["straight", "swing", "shuffle", "swing 16"];
16
6
  /** `n/d` with n from 1 to 32 and d in 2, 4, 8, 16. */
17
7
  export function parseMeter(text) {
@@ -160,10 +160,9 @@ function oldFormat(text, line) {
160
160
  const credit = nearCredit(text, line);
161
161
  if (credit)
162
162
  return credit;
163
- const near = /^(\w+)\s*:\s*(.*)$/.exec(text);
164
- const name = near?.[1] ? NEAR_DIRECTIVES[near[1].toLowerCase()] : undefined;
165
- if (near && name)
166
- return warn(`not a directive; did you mean ${name}:?`, `${name}: ${near[2]}`);
163
+ const directive = nearDirective(text);
164
+ if (directive)
165
+ return warn(directive.message, directive.suggestion);
167
166
  const undeclared = undeclaredLabel(text, line);
168
167
  if (undeclared)
169
168
  return undeclared;
@@ -175,6 +174,19 @@ function oldFormat(text, line) {
175
174
  return warn("chords outside a bar line are text", `| ${words.join(" | ")} |`);
176
175
  return null;
177
176
  }
177
+ /** A misnamed directive (`meter:`), or `title:` for the `#` title (Kevin's ruling, 2026-11-07). */
178
+ function nearDirective(text) {
179
+ const near = /^(\w+)\s*:\s*(.*)$/.exec(text);
180
+ const [, word = "", value = ""] = near ?? [];
181
+ const lower = word.toLowerCase();
182
+ if (lower === "title" && value)
183
+ return { message: "not a directive; the title is the # line", suggestion: `# ${value}` };
184
+ // Own keys only: `constructor:` is not a directive's near miss.
185
+ const name = Object.hasOwn(NEAR_DIRECTIVES, lower) ? NEAR_DIRECTIVES[lower] : undefined;
186
+ if (!near || !name)
187
+ return null;
188
+ return { message: `not a directive; did you mean ${name}:?`, suggestion: `${name}: ${value}` };
189
+ }
178
190
  /** `D \| A \|` (an editor's escaping) as the bar line it would be, if it reads cleanly. */
179
191
  function escapedBarLine(text) {
180
192
  if (!text.includes("\\|"))
@@ -6,6 +6,7 @@ export { beatsOf, DIRECTIVE_NAMES, parseDirectiveLine, parseMeter } from "./dire
6
6
  export { readDocument } from "./document.js";
7
7
  export { expand, flattenBars, MAX_EXPANDED_BARS } from "./expand.js";
8
8
  export { CLEF_NAMES, type ClefName, INSTRUMENTS, type InstrumentInfo, type InstrumentName, instrumentInfo, type WrittenInterval, } from "./instruments.js";
9
+ export { conventionalKey, keyFromText, printKey, spellPitch } from "./keys.js";
9
10
  export { MAX_LINES } from "./lines.js";
10
11
  export { extractPart, parseChart } from "./parse.js";
11
12
  export { projectPart } from "./parts.js";
@@ -6,6 +6,7 @@ export { beatsOf, DIRECTIVE_NAMES, parseDirectiveLine, parseMeter } from "./dire
6
6
  export { readDocument } from "./document.js";
7
7
  export { expand, flattenBars, MAX_EXPANDED_BARS } from "./expand.js";
8
8
  export { CLEF_NAMES, INSTRUMENTS, instrumentInfo, } from "./instruments.js";
9
+ export { conventionalKey, keyFromText, printKey, spellPitch } from "./keys.js";
9
10
  export { MAX_LINES } from "./lines.js";
10
11
  export { extractPart, parseChart } from "./parse.js";
11
12
  export { projectPart } from "./parts.js";
@@ -0,0 +1,16 @@
1
+ import type { Key, Mode } from "./types.js";
2
+ export declare const MODES: Mode[];
3
+ export declare const SHARPS: string[];
4
+ export declare const alterOf: (note: string) => number;
5
+ /** Double sharps and flats are written as the plain note: Fx is G, Ebb is D. */
6
+ export declare function plain(note: string): string;
7
+ /** Sharps (positive) or flats (negative) in a key's signature. */
8
+ export declare const signature: (tonic: string, mode: Mode) => number;
9
+ /** A pitch class spelled in a key (or, with no key, from transposeChart's table). */
10
+ export declare function spellPitch(pitchClass: number, key: Key | null): string;
11
+ /** The same key spelled with the fewest accidentals; a tie keeps the spelling given. */
12
+ export declare function conventionalKey(key: Key): Key;
13
+ /** A key as `key:` writes it: `D`, `F#m`, `A mixolydian`. */
14
+ export declare function printKey(k: Key): string;
15
+ /** A key as people and detectors write it: `F♯ minor`, `Bb Maj`, `C#m`, `A Mixolydian`; null otherwise. */
16
+ export declare function keyFromText(text: string): Key | null;
@@ -0,0 +1,119 @@
1
+ import { noteSemitone, transpose } from "../chords/intervals.js";
2
+ export const MODES = [
3
+ "major",
4
+ "minor",
5
+ "ionian",
6
+ "dorian",
7
+ "phrygian",
8
+ "lydian",
9
+ "mixolydian",
10
+ "aeolian",
11
+ "locrian",
12
+ ];
13
+ export const SHARPS = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
14
+ const FLATS = ["C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"];
15
+ /** A chart with no key spells each root from this table. */
16
+ const TABLE = ["C", "C#", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B"];
17
+ /** Each letter's place on the circle of fifths, and each mode's offset from its parent major. */
18
+ const FIFTHS = { F: -1, C: 0, G: 1, D: 2, A: 3, E: 4, B: 5 };
19
+ const MODE_FIFTHS = {
20
+ lydian: 1,
21
+ major: 0,
22
+ ionian: 0,
23
+ mixolydian: -1,
24
+ dorian: -2,
25
+ minor: -3,
26
+ aeolian: -3,
27
+ phrygian: -4,
28
+ locrian: -5,
29
+ };
30
+ const mod = (n, m) => ((n % m) + m) % m;
31
+ export const alterOf = (note) => (note.includes("#") ? 1 : -1) * (note.length - 1);
32
+ /** Double sharps and flats are written as the plain note: Fx is G, Ebb is D. */
33
+ export function plain(note) {
34
+ if (!/##|bb/.test(note))
35
+ return note;
36
+ return (note.includes("#") ? SHARPS : FLATS)[noteSemitone(note)] ?? note;
37
+ }
38
+ /** Sharps (positive) or flats (negative) in a key's signature. */
39
+ export const signature = (tonic, mode) => (FIFTHS[tonic[0] ?? "C"] ?? 0) + 7 * alterOf(tonic) + MODE_FIFTHS[mode];
40
+ const MAJOR_SCALE = [0, 2, 4, 5, 7, 9, 11];
41
+ /** The major-scale degree each mode starts on (0 = ionian). */
42
+ const ROTATION = {
43
+ major: 0,
44
+ ionian: 0,
45
+ dorian: 1,
46
+ phrygian: 2,
47
+ lydian: 3,
48
+ mixolydian: 4,
49
+ minor: 5,
50
+ aeolian: 5,
51
+ locrian: 6,
52
+ };
53
+ /** A mode's semitone offsets from its tonic, by scale degree. */
54
+ const scaleOf = (mode) => {
55
+ const start = ROTATION[mode];
56
+ const root = MAJOR_SCALE[start] ?? 0;
57
+ return MAJOR_SCALE.map((_, i) => mod((MAJOR_SCALE[(start + i) % 7] ?? 0) - root, 12));
58
+ };
59
+ /** Notes outside the mode: the major-scale map (bII, bIII, #IV, bVI, bVII). */
60
+ const OUTSIDE = {
61
+ 0: { degree: 1, alter: 0 },
62
+ 1: { degree: 2, alter: -1 },
63
+ 2: { degree: 2, alter: 0 },
64
+ 3: { degree: 3, alter: -1 },
65
+ 4: { degree: 3, alter: 0 },
66
+ 5: { degree: 4, alter: 0 },
67
+ 6: { degree: 4, alter: 1 },
68
+ 7: { degree: 5, alter: 0 },
69
+ 8: { degree: 6, alter: -1 },
70
+ 9: { degree: 6, alter: 0 },
71
+ 10: { degree: 7, alter: -1 },
72
+ 11: { degree: 7, alter: 0 },
73
+ };
74
+ /** A pitch class spelled in a key (or, with no key, from transposeChart's table). */
75
+ export function spellPitch(pitchClass, key) {
76
+ const pc = mod(pitchClass, 12);
77
+ if (!key)
78
+ return TABLE[pc] ?? "C";
79
+ const s = mod(pc - noteSemitone(key.tonic), 12);
80
+ const degree = scaleOf(key.mode).indexOf(s);
81
+ const interval = degree >= 0
82
+ ? { degree: degree + 1, alter: s - (MAJOR_SCALE[degree] ?? 0) }
83
+ : (OUTSIDE[s] ?? { degree: 1, alter: 0 });
84
+ return plain(transpose(key.tonic, interval));
85
+ }
86
+ /** The same key spelled with the fewest accidentals; a tie keeps the spelling given. */
87
+ export function conventionalKey(key) {
88
+ const pc = noteSemitone(key.tonic);
89
+ let best = key.tonic;
90
+ for (const t of [SHARPS[pc], FLATS[pc]])
91
+ if (t && Math.abs(signature(t, key.mode)) < Math.abs(signature(best, key.mode)))
92
+ best = t;
93
+ return { tonic: best, mode: key.mode };
94
+ }
95
+ /** A key as `key:` writes it: `D`, `F#m`, `A mixolydian`. */
96
+ export function printKey(k) {
97
+ if (k.mode === "major")
98
+ return k.tonic;
99
+ if (k.mode === "minor")
100
+ return `${k.tonic}m`;
101
+ return `${k.tonic} ${k.mode}`;
102
+ }
103
+ const WORDS = /^(?:maj|min|major|minor|ionian|dorian|phrygian|lydian|mixolydian|aeolian|locrian)$/i;
104
+ const WORD_MODE = { maj: "major", min: "minor" };
105
+ /** A key as people and detectors write it: `F♯ minor`, `Bb Maj`, `C#m`, `A Mixolydian`; null otherwise. */
106
+ export function keyFromText(text) {
107
+ const m = /^([A-Ga-g])([#b♯♭]?)(m|\s*[A-Za-z]{3,})?$/.exec(text.trim().replace(/\s+/g, " "));
108
+ if (!m?.[1])
109
+ return null;
110
+ const tonic = `${m[1].toUpperCase()}${(m[2] ?? "").replace("♯", "#").replace("♭", "b")}`;
111
+ if (m[3] === undefined)
112
+ return { tonic, mode: "major" };
113
+ if (m[3] === "m")
114
+ return { tonic, mode: "minor" };
115
+ const word = m[3].trim().toLowerCase();
116
+ if (!WORDS.test(word))
117
+ return null;
118
+ return { tonic, mode: WORD_MODE[word] ?? word };
119
+ }
@@ -2,6 +2,7 @@ import { isBar } 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
+ import { printKey } from "./keys.js";
5
6
  import { extractPart, parseChart } from "./parse.js";
6
7
  /** A slot with no attack of its own continues whatever sounds before it. A repeated chord name is a re-attack. */
7
8
  function continues(sounding, s) {
@@ -112,13 +113,6 @@ export function printPasses(passes) {
112
113
  return runs.flatMap((r) => (r.length >= 3 ? [`${r[0]}-${r.at(-1)}`] : r.map(String))).join(",");
113
114
  }
114
115
  const printRepeat = (r) => (r === null ? "" : r === "open" ? " x ..." : ` x${r}`);
115
- function printKey(k) {
116
- if (k.mode === "major")
117
- return k.tonic;
118
- if (k.mode === "minor")
119
- return `${k.tonic}m`;
120
- return `${k.tonic} ${k.mode}`;
121
- }
122
116
  function printTempoChange(c) {
123
117
  if (c.kind === "a tempo")
124
118
  return "a tempo";
@@ -3,42 +3,14 @@ import { parseNoteSet } from "../chords/noteSet.js";
3
3
  import { parseChord } from "../chords/parse.js";
4
4
  import { printChord } from "../chords/print.js";
5
5
  import { parseDirectiveLine } from "./directives.js";
6
+ import { alterOf, conventionalKey, plain, SHARPS, spellPitch } from "./keys.js";
6
7
  import { parseChart } from "./parse.js";
7
8
  import { printParsed } from "./print.js";
8
- const SHARPS = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
9
- const FLATS = ["C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"];
10
- /** A chart with no key spells each root from this table. */
11
- const TABLE = ["C", "C#", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B"];
12
- /** Each letter's place on the circle of fifths, and each mode's offset from its parent major. */
13
- const FIFTHS = { F: -1, C: 0, G: 1, D: 2, A: 3, E: 4, B: 5 };
14
- const MODE_FIFTHS = {
15
- lydian: 1,
16
- major: 0,
17
- ionian: 0,
18
- mixolydian: -1,
19
- dorian: -2,
20
- minor: -3,
21
- aeolian: -3,
22
- phrygian: -4,
23
- locrian: -5,
24
- };
25
9
  const mod = (n, m) => ((n % m) + m) % m;
26
- const alterOf = (note) => (note.includes("#") ? 1 : -1) * (note.length - 1);
27
- /** Double sharps and flats are written as the plain note: Fx is G, Ebb is D. */
28
- function plain(note) {
29
- if (!/##|bb/.test(note))
30
- return note;
31
- return (note.includes("#") ? SHARPS : FLATS)[noteSemitone(note)] ?? note;
32
- }
33
- /** Sharps (positive) or flats (negative) in a key's signature. */
34
- const signature = (tonic, mode) => (FIFTHS[tonic[0] ?? "C"] ?? 0) + 7 * alterOf(tonic) + MODE_FIFTHS[mode];
35
10
  /** The key `semitones` away, spelled with the fewest accidentals; sharps win a tie (F# over Gb). */
36
11
  function nearestKey(key, semitones) {
37
12
  const pc = mod(noteSemitone(key.tonic) + semitones, 12);
38
- const [a = "C", b = "C"] = [SHARPS[pc], FLATS[pc]];
39
- const sa = signature(a, key.mode);
40
- const sb = signature(b, key.mode);
41
- return Math.abs(sb) < Math.abs(sa) || (Math.abs(sb) === Math.abs(sa) && sb > sa) ? b : a;
13
+ return conventionalKey({ tonic: SHARPS[pc] ?? "C", mode: key.mode }).tonic;
42
14
  }
43
15
  function firstKey(parsed) {
44
16
  for (const l of parsed.lines)
@@ -68,7 +40,7 @@ function moveBy(key, semitones) {
68
40
  if (!Number.isInteger(semitones))
69
41
  return fail("transpose by a whole number of semitones", String(semitones));
70
42
  if (!key)
71
- return { spell: (n) => TABLE[mod(noteSemitone(n) + semitones, 12)] ?? n, semitones };
43
+ return { spell: (n) => spellPitch(noteSemitone(n) + semitones, null), semitones };
72
44
  const interval = intervalBetween(key.tonic, nearestKey(key, semitones));
73
45
  return { spell: (n) => plain(transpose(n, interval)), semitones };
74
46
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barmark",
3
- "version": "0.17.1",
3
+ "version": "0.19.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": {