barmark 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,122 @@
1
+ const passesToken = (b) => `|${(b.ending ?? []).join(",")}`;
2
+ const asLine = (line) => ({ kind: "line", line, repeat: null });
3
+ const highestPass = (endings) => Math.max(...endings.flatMap((b) => b.ending ?? []));
4
+ /** Every pass from 1 to the highest has exactly one ending, and the highest is at least 2. */
5
+ function passProblems(endings, last) {
6
+ const highest = highestPass(endings);
7
+ if (highest < 2)
8
+ return [[last, "a repeat with endings plays at least two passes"]];
9
+ const problems = [];
10
+ for (let p = 1; p < highest + 1; p++) {
11
+ const n = endings.filter((b) => b.ending?.includes(p)).length;
12
+ if (n !== 1)
13
+ problems.push([last, `pass ${p} has ${n ? "two endings" : "no ending"}`]);
14
+ }
15
+ if (!last.ending?.includes(highest))
16
+ problems.push([last, `the last ending must be the one for pass ${highest}`]);
17
+ return problems;
18
+ }
19
+ /** Every ending but the last goes back with `:|`; the last plays on. */
20
+ function closeProblems(endings, last) {
21
+ return endings.flatMap((b) => {
22
+ 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
+ });
26
+ }
27
+ /** A repeat with its endings, or, if they have problems, each line played once. */
28
+ function closeEndings(e, error) {
29
+ const last = e.endings.at(-1);
30
+ if (!last)
31
+ return [];
32
+ const problems = [...passProblems(e.endings, last), ...closeProblems(e.endings, last)];
33
+ for (const [b, message] of problems)
34
+ error(b.line, message, passesToken(b));
35
+ const between = e.between.map((x) => asLine(x.line));
36
+ 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
+ }));
42
+ const repeat = highestPass(e.endings);
43
+ return [{ kind: "bracket", line: e.line, entries: e.entries, repeat, endings }, ...between];
44
+ }
45
+ /** An ending line starts the endings of the open repeat, or continues them. */
46
+ function takeEnding(st, bars, error) {
47
+ if (bars.repeat !== null)
48
+ error(bars.line, "x N on an ending: the endings give the count", passesToken(bars));
49
+ if (st.open)
50
+ st.endings = { ...st.open, endings: [bars], between: [] };
51
+ else if (st.endings)
52
+ st.endings.endings.push(bars);
53
+ else {
54
+ error(bars.line, "an ending follows the bars of a |: … :| repeat", passesToken(bars));
55
+ st.items.push(asLine(bars));
56
+ }
57
+ st.open = null;
58
+ }
59
+ /** `|:` opens a repeat, unless one is open already. */
60
+ function openRepeat(st, bars, error) {
61
+ if (st.open)
62
+ error(bars.line, "|: inside another |:", "|:");
63
+ else
64
+ st.open = { line: bars.line, entries: [] };
65
+ }
66
+ /** `:|` closes the open repeat; with none open it is an error, and its line plays once. */
67
+ function closeRepeat(st, bars, error) {
68
+ if (!st.open) {
69
+ error(bars.line, ":| has no |: before it in this section", ":|");
70
+ st.items.push(asLine(bars));
71
+ return;
72
+ }
73
+ const { line, entries } = st.open;
74
+ entries.push({ line: bars, repeat: null });
75
+ st.items.push({ kind: "bracket", line, entries, repeat: bars.repeat ?? 2, endings: [] });
76
+ st.open = null;
77
+ }
78
+ /** Any other line: it opens or closes a repeat, or belongs to the open one, or stands alone. */
79
+ function takeLine(st, l, error) {
80
+ if (l.kind === "bars" && l.opens)
81
+ openRepeat(st, l, error);
82
+ if (l.kind === "bars" && l.closes)
83
+ closeRepeat(st, l, error);
84
+ else
85
+ addEntry(st, { line: l, repeat: l.kind === "bars" ? l.repeat : null });
86
+ }
87
+ /** A line inside the open repeat belongs to it; any other stands alone. */
88
+ function addEntry(st, entry) {
89
+ if (st.open)
90
+ st.open.entries.push(entry);
91
+ else
92
+ st.items.push({ kind: "line", ...entry });
93
+ }
94
+ /**
95
+ * Pair `|:` and `:|` within one section's lines, with the endings that
96
+ * follow a repeat (grammar 5.1). Problems are reported, and what cannot
97
+ * pair plays once.
98
+ */
99
+ export function pairRepeats(lines, error) {
100
+ const st = { items: [], open: null, endings: null };
101
+ const finish = () => {
102
+ if (st.endings)
103
+ st.items.push(...closeEndings(st.endings, error));
104
+ st.endings = null;
105
+ };
106
+ for (const l of lines) {
107
+ if (l.kind === "bars" && l.ending)
108
+ takeEnding(st, l, error);
109
+ else if (st.endings && l.kind === "text")
110
+ st.endings.between.push({ line: l, repeat: null });
111
+ else {
112
+ finish();
113
+ takeLine(st, l, error);
114
+ }
115
+ }
116
+ finish();
117
+ if (st.open) {
118
+ error(st.open.line, "|: is never closed in this section", "|:");
119
+ st.items.push(...st.open.entries.map((e) => ({ kind: "line", ...e })));
120
+ }
121
+ return st.items;
122
+ }
@@ -100,7 +100,14 @@ function moveChord(chord, move, warn) {
100
100
  return r.ok ? r.value : chord;
101
101
  }
102
102
  function moveCells(cells, move, warn) {
103
- const simple = (s) => s.kind === "chord" ? { kind: "chord", chord: moveChord(s.chord, move, warn) } : s;
103
+ const simple = (s) => {
104
+ if (s.kind !== "chord")
105
+ return s;
106
+ const chord = moveChord(s.chord, move, warn);
107
+ return s.voicing
108
+ ? { ...s, chord, voicing: moveNoteSet(s.voicing, move, warn) }
109
+ : { ...s, chord };
110
+ };
104
111
  const slot = (s) => s.kind === "group" ? { kind: "group", members: s.members.map(simple) } : simple(s);
105
112
  return cells.map((c) => (c.kind === "slots" ? { ...c, slots: c.slots.map(slot) } : c));
106
113
  }
@@ -39,16 +39,33 @@ export type Directives = {
39
39
  */
40
40
  swingPercent?: number;
41
41
  };
42
- /** A chord slot holds a chord symbol or a note set; `chord.kind` tells which. */
42
+ /** `>` accents a chord; `^` makes it a hit, short and accented (grammar 2.7). */
43
+ export type Articulation = "accent" | "hit";
44
+ /**
45
+ * How early a slot arrives (grammar 2.8): `<` an eighth note, `<<` a
46
+ * sixteenth, taken from the slot played just before it.
47
+ */
48
+ export type Push = "eighth" | "sixteenth";
49
+ /**
50
+ * A chord slot holds a chord symbol or a note set; `chord.kind` tells
51
+ * which. `voicing` is the exact notes written after a chord's name
52
+ * (`Cmaj7{E3 G3 B3}`, grammar 4.2). The optional fields are present only
53
+ * when written.
54
+ */
43
55
  export type SimpleSlot = {
44
56
  kind: "chord";
45
57
  chord: ChordRecord;
58
+ voicing?: ChordRecord;
59
+ articulation?: Articulation;
60
+ push?: Push;
46
61
  } | {
47
62
  kind: "hold";
48
63
  } | {
49
64
  kind: "nc";
65
+ push?: Push;
50
66
  } | {
51
67
  kind: "silence";
68
+ push?: Push;
52
69
  } | {
53
70
  kind: "unknown";
54
71
  };
@@ -56,15 +73,55 @@ export type Slot = SimpleSlot | {
56
73
  kind: "group";
57
74
  members: SimpleSlot[];
58
75
  };
59
- /** `meter` is a one-bar `[n/d]` override. */
76
+ /**
77
+ * A mark between bars (grammar 5.2). A jump goes back to the chart's first
78
+ * bar (`D.C.`) or to the segno (`D.S.`), then plays to the end, to `Fine`
79
+ * (`al Fine`) or to `To Coda` (`al Coda`).
80
+ */
81
+ export type Direction = {
82
+ kind: "segno";
83
+ } | {
84
+ kind: "coda";
85
+ } | {
86
+ kind: "to coda";
87
+ } | {
88
+ kind: "fine";
89
+ } | {
90
+ kind: "jump";
91
+ to: "start" | "segno";
92
+ al: "fine" | "coda" | null;
93
+ };
94
+ /**
95
+ * Quoted words on a bar (grammar 2.6), placed before the slot numbered
96
+ * `at` (0-based); `at` equal to the slot count places them after the last
97
+ * slot. They carry no musical meaning.
98
+ */
99
+ export type Words = {
100
+ text: string;
101
+ at: number;
102
+ };
103
+ /**
104
+ * `meter` is a one-bar `[n/d]` override. `...`, a direction and a
105
+ * rehearsal mark are not bars. `words` is present only when written.
106
+ */
60
107
  export type Cell = {
61
108
  kind: "slots";
62
109
  meter: Meter | null;
63
110
  slots: Slot[];
111
+ words?: Words[];
64
112
  } | {
65
113
  kind: "simile";
114
+ words?: Words[];
66
115
  } | {
67
116
  kind: "fermata";
117
+ } | {
118
+ kind: "direction";
119
+ direction: Direction;
120
+ }
121
+ /** `@B`: a mark on the bar after it (grammar 2.5). */
122
+ | {
123
+ kind: "rehearsal";
124
+ label: string;
68
125
  };
69
126
  export type Repeat = number | "open" | null;
70
127
  export type Line = {
@@ -88,6 +145,8 @@ export type Line = {
88
145
  closes: boolean;
89
146
  cells: Cell[];
90
147
  repeat: Repeat;
148
+ /** The passes an ending plays on (grammar 5.1), in order; null for any other bar line. */
149
+ ending: number[] | null;
91
150
  } | {
92
151
  kind: "text";
93
152
  line: number;
@@ -130,6 +189,10 @@ export type PlayedBar = {
130
189
  swingPercent?: number;
131
190
  /** `%` resolved to the copied slots; holds stay holds. */
132
191
  slots: Slot[];
192
+ /** The rehearsal mark written just before this bar (`@B` gives "B"); absent when none. */
193
+ rehearsal?: string;
194
+ /** Words written on this bar; absent when none. `%` copies chords, not words. */
195
+ words?: Words[];
133
196
  };
134
197
  /** An open repeat shows one pass; the number of passes is unknown. */
135
198
  export type ChartEvent = {
@@ -1,7 +1,7 @@
1
1
  import { formatInterval, intervalBetween, intervalKey, parseInterval, transpose, } from "./intervals.js";
2
2
  import { printSuffix } from "./print.js";
3
3
  import { enumerateSuffixes, intervalSetKey } from "./suffixes.js";
4
- import { byDegree, chordIntervals, HARTE_SHORTHANDS } from "./vocabulary.js";
4
+ import { byDegree, chordIntervals, HARTE_SHORTHANDS, isOmission, } from "./vocabulary.js";
5
5
  /**
6
6
  * The Harte label for a parsed chord or note set: the largest shorthand
7
7
  * contained in the chord, the remaining intervals in parentheses, and the
@@ -10,7 +10,8 @@ import { byDegree, chordIntervals, HARTE_SHORTHANDS } from "./vocabulary.js";
10
10
  */
11
11
  export function toHarte(r) {
12
12
  const root = r.root ?? r.bass;
13
- const keys = new Set(r.intervals.map(intervalKey));
13
+ const left = omitted(r);
14
+ const keys = new Set([...r.intervals, ...left].map(intervalKey));
14
15
  const written = new Set(r.intervals.map(formatInterval));
15
16
  // Most intervals wins; ties go to the shorthand naming more degrees exactly as
16
17
  // written (sus4 over sus2 in a 9sus4, whose 9 only shares the 2's pitch class).
@@ -26,10 +27,21 @@ export function toHarte(r) {
26
27
  }
27
28
  const { name: shorthand, used } = best;
28
29
  const added = r.intervals.filter((i) => !used.has(intervalKey(i))).sort(byDegree);
29
- const list = added.length ? `(${added.map(formatInterval).join(",")})` : "";
30
+ // Harte marks a tone its shorthand has and the chord leaves out with `*` (`C:7(*3)`).
31
+ const out = left.filter((i) => used.has(intervalKey(i))).map((i) => `*${formatInterval(i)}`);
32
+ const items = [...added.map(formatInterval), ...out];
33
+ const list = items.length ? `(${items.join(",")})` : "";
30
34
  const bass = r.bass === root ? "" : `/${formatInterval(intervalBetween(root, r.bass))}`;
31
35
  return `${root}:${shorthand}${list}${bass}`;
32
36
  }
37
+ /** The intervals a chord's `no3`/`no5` leave out, so its label can name them. */
38
+ function omitted(r) {
39
+ if (!r.parts?.tones.some(isOmission))
40
+ return [];
41
+ const kept = { ...r.parts, tones: r.parts.tones.filter((t) => !isOmission(t)) };
42
+ const keys = new Set(r.intervals.map(intervalKey));
43
+ return chordIntervals(kept, "").intervals.filter((i) => !keys.has(intervalKey(i)));
44
+ }
33
45
  const shape = (quality, extension = null, tones = [], sus = null) => ({ quality, extension, sus, tones });
34
46
  const INTENDED = {
35
47
  maj: shape(""),
@@ -1,7 +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 { ALIASES, chordIntervals, EXTENSIONS, rejection, TONES, validateParts, } from "./vocabulary.js";
4
+ import { ALIASES, chordIntervals, EXTENSIONS, isOmission, OMISSIONS, rejection, TONES, validateParts, } from "./vocabulary.js";
5
5
  const ROOT = /^[A-G][#b]?/;
6
6
  const INLINE_ALTERATION = /^(b5|#5|b9|#9|#11|b13)/;
7
7
  /** Splits a symbol into its parts, or names the text it could not read. */
@@ -45,8 +45,9 @@ function tokenize(symbol) {
45
45
  const paren = /^\(([^)]*)\)/.exec(rest);
46
46
  if (paren) {
47
47
  for (const t of (paren[1] ?? "").split(",").map((x) => x.trim())) {
48
- if (!TONES.includes(t))
49
- return `"${t}" is not a tone a parenthesis can add`;
48
+ const problem = toneProblem(t, tones);
49
+ if (problem)
50
+ return problem;
50
51
  tones.push(t);
51
52
  }
52
53
  rest = rest.slice(paren[0].length);
@@ -61,6 +62,43 @@ function tokenize(symbol) {
61
62
  return `cannot read "${rest}"`;
62
63
  return { root, quality, extension: ext, sus, tones, bass };
63
64
  }
65
+ /** Why a tone can't go in a chord's parentheses after `before`; null when it can. */
66
+ function toneProblem(tone, before) {
67
+ if (isOmission(tone)) {
68
+ if (!OMISSIONS.includes(tone))
69
+ return `"${tone}": a chord leaves out only its 3rd or 5th (no3, no5)`;
70
+ return before.includes(tone) ? `${tone} is written twice` : null;
71
+ }
72
+ return TONES.includes(tone) ? null : `"${tone}" is not a tone a parenthesis can add`;
73
+ }
74
+ const ORDINAL = { 3: "3rd", 5: "5th" };
75
+ /**
76
+ * The intervals once `no3`/`no5` leave out a tone, or why they can't: the
77
+ * chord must have that tone, unaltered by its own parentheses.
78
+ */
79
+ function omit(intervals, parts, symbol) {
80
+ let out = intervals;
81
+ for (const tone of parts.tones.filter(isOmission)) {
82
+ const degree = Number(tone.slice(2));
83
+ const fail = (why) => ({ message: `${symbol}: ${why}`, token: symbol });
84
+ const altered = parts.tones.some((t) => !isOmission(t) && Number(t.replace(/^[#b]/, "")) === degree && /^[#b]/.test(t));
85
+ if (altered)
86
+ return fail(`the ${ORDINAL[degree]} is altered and left out`);
87
+ if (!out.some((i) => i.degree === degree)) {
88
+ const base = printChord({ ...parts, tones: parts.tones.filter((t) => !isOmission(t)) });
89
+ return fail(`${base} has no ${ORDINAL[degree]} to leave out`);
90
+ }
91
+ out = out.filter((i) => i.degree !== degree);
92
+ }
93
+ return out;
94
+ }
95
+ /** A triad with no third is the power chord: `C(no3)` is `C5`, one spelling (grammar 3). */
96
+ function powerChord(parts) {
97
+ const triad = (parts.quality === "" || parts.quality === "m") && !parts.extension && !parts.sus;
98
+ if (!triad || !parts.tones.includes("no3"))
99
+ return parts;
100
+ return { ...parts, quality: "5", tones: parts.tones.filter((t) => t !== "no3") };
101
+ }
64
102
  /**
65
103
  * Logic Pro's spellings (Appendix A.5): groups in a row are one list
66
104
  * (`(5)(7)` is `(5,7)`), and `5` in a bare root's group is the power chord
@@ -86,6 +124,8 @@ function normalizeSymbol(symbol) {
86
124
  for (const [pattern, replacement] of ALIASES)
87
125
  rest = rest.replace(pattern, replacement);
88
126
  rest = logicGroups(rest);
127
+ // `(omit3)` and `(omit 3)` are `(no3)`.
128
+ rest = rest.replace(/(?<=[(,]\s*)omit\s*(\d+)(?=\s*[,)])/g, "no$1");
89
129
  // `(add9)` is `(9)`: inside a group, `add` before a tone it may add is dropped.
90
130
  rest = rest.replace(/(?<=[(,]\s*)add(2|4|9|11)(?=\s*[,)])/g, "$1");
91
131
  // A bare `add9` outside any group; what is left inside one is the tokenizer's to name.
@@ -108,14 +148,19 @@ export function parseChord(symbol) {
108
148
  const normal = normalizeSymbol(symbol);
109
149
  if (!("text" in normal))
110
150
  return { ok: false, error: normal };
111
- const parts = tokenize(normal.text);
112
- if (typeof parts === "string") {
113
- return { ok: false, error: { message: `${symbol}: ${parts}`, token: symbol } };
151
+ const read = tokenize(normal.text);
152
+ if (typeof read === "string") {
153
+ return { ok: false, error: { message: `${symbol}: ${read}`, token: symbol } };
114
154
  }
155
+ const parts = powerChord(read);
115
156
  const invalid = validateParts(parts, symbol);
116
157
  if (invalid)
117
158
  return { ok: false, error: invalid };
118
- const { intervals, warnings, alteredOpen } = chordIntervals(parts, symbol);
159
+ const added = chordIntervals({ ...parts, tones: parts.tones.filter((t) => !isOmission(t)) }, symbol);
160
+ const { warnings, alteredOpen } = added;
161
+ const intervals = omit(added.intervals, parts, symbol);
162
+ if (!Array.isArray(intervals))
163
+ return { ok: false, error: intervals };
119
164
  const pitches = intervals.map((i) => transpose(parts.root, i));
120
165
  if (parts.bass && !pitches.includes(parts.bass))
121
166
  pitches.push(parts.bass);
@@ -1,6 +1,9 @@
1
- import { byDegree, toneInterval } from "./vocabulary.js";
2
- /** The tones in canonical order (by degree), as the canonical spelling lists them. */
3
- const sortTones = (tones) => [...tones].sort((a, b) => byDegree(toneInterval(a), toneInterval(b)));
1
+ import { byDegree, isOmission, toneInterval } from "./vocabulary.js";
2
+ /** The tones in canonical order: added tones by degree, then what is left out (`(b9,no5)`). */
3
+ const sortTones = (tones) => [
4
+ ...tones.filter((t) => !isOmission(t)).sort((a, b) => byDegree(toneInterval(a), toneInterval(b))),
5
+ ...tones.filter(isOmission).sort(),
6
+ ];
4
7
  /** The parts as the canonical spelling has them: the same parts, tones sorted. */
5
8
  export function canonicalParts(parts) {
6
9
  return { ...parts, tones: sortTones(parts.tones) };
@@ -18,6 +18,9 @@ export declare const VALID_EXTENSIONS: Record<Quality, (Extension | null)[]>;
18
18
  export declare const SUS_ALLOWED_WITH: (Extension | null)[];
19
19
  /** Tones a parenthesis may hold. Tone `7` means the interval b7. */
20
20
  export declare const TONES: string[];
21
+ /** Tones a parenthesis may leave out (grammar 3): the 3rd or the 5th. */
22
+ export declare const OMISSIONS: string[];
23
+ export declare const isOmission: (tone: string) => boolean;
21
24
  export declare const toneInterval: (tone: string) => Interval;
22
25
  /** Degree order, then flat before natural before sharp. */
23
26
  export declare const byDegree: (a: Interval, b: Interval) => number;
@@ -41,6 +41,9 @@ export const VALID_EXTENSIONS = {
41
41
  export const SUS_ALLOWED_WITH = [null, "7", "9", "13"];
42
42
  /** Tones a parenthesis may hold. Tone `7` means the interval b7. */
43
43
  export const TONES = ["2", "4", "6", "7", "9", "11", "13", "b5", "#5", "b9", "#9", "#11", "b13"];
44
+ /** Tones a parenthesis may leave out (grammar 3): the 3rd or the 5th. */
45
+ export const OMISSIONS = ["no3", "no5"];
46
+ export const isOmission = (tone) => tone.startsWith("no");
44
47
  export const toneInterval = (tone) => {
45
48
  const i = parseInterval(tone === "7" ? "b7" : tone);
46
49
  if (!i)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barmark",
3
- "version": "0.10.0",
3
+ "version": "0.12.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": {