barmark
Reads a chart (bars in play order, with problems by line), prints it in standard form, transposes it, converts Harte labels.
When to use it: Anything that reads or writes charts. The others build on it.
- Version
0.29.1- Install
npm install barmark
Example
The example song, and the same chart from transposeChart(text, { to: "E" }).
example-song.chart.md
# Example Song
key: D, time: 4/4, tempo: 145
## Verse
|: D | A | Bm | G :|
| Em | / | A | A7 |
## Chorus
| G / D / | A | Bm / / A | G |
Transposed to E
# Example Song
key: E, time: 4/4, tempo: 145
## Verse
|: E | B | C#m | A :|
| F#m | / | B | B7 |
## Chorus
| A E | B | C#m / / B | A |
Markdown-inspired plain-text notation for chord charts: the bar grid
musicians already write (| D | A |), specified precisely enough for
machines.
# Example Song
key: D, time: 4/4, tempo: 145
## Verse
|: D | A | Bm | G :|
| Em | / | A | A7 |
## Chorus
| G / D / | A | Bm / / A | G |
## Verse
## Chorus x2
A Barmark file is a markdown file, with the extension .chart.md. The
grammar is docs/grammar-v0.1-draft.md
(draft v0.1, for review), and examples/ has a full chart.
Install
npm install barmark
ESM only, Node 20 or later (or Bun, Deno and browsers), with TypeScript declarations included and no runtime dependencies.
Use
import {
conventionalKey,
degreeOf,
extractPart,
harteToBarmark,
keyFromText,
nameNotes,
parseChart,
parseChord,
printChart,
printKey,
printParsed,
printPart,
projectPart,
spellPitch,
transposeChart,
} from "barmark";
const chart = parseChart(text);
chart.title; // "Example Song"
chart.parts; // [{ label: "Gtr", name: "Electric Guitar 1" }] from part: Gtr = Electric Guitar 1, in score order
chart.credits; // { composer: ["Kevin Peckham"], lyricist: [], arranger: [], copyright: [] } from composer: Kevin Peckham
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)
chart.pickup; // true when the first written bar is a pickup (time: 4/4 then | [1/4] G | C |): it is bar 0
chart.sections; // each section as played, with its first and last bar
chart.diagnostics; // errors and warnings, each with a line number
printChart(text); // the chart in canonical form (same meaning, standard spelling)
printParsed(text, chart); // the same, from a parse you already have
transposeChart("key: D\n| D | A | Bm | G |", { to: "Eb" }).text; // "key: Eb\n| Eb | Bb | Cm | Ab |\n"
transposeChart(text, { semitones: -2 }); // { text, diagnostics }
keyFromText("F♯ minor"); // { tonic: "F#", mode: "minor" }; null when it isn't a key
conventionalKey({ tonic: "Ab", mode: "minor" }); // { tonic: "G#", mode: "minor" }: the spelling with fewest accidentals
printKey({ tonic: "F#", mode: "minor" }); // "F#m", as `key:` writes it
spellPitch(10, { tonic: "D", mode: "major" }); // "Bb": a pitch class (0 = C) spelled in a key; null key uses C C# D Eb ...
degreeOf("C", { tonic: "D", mode: "major" }); // { degree: 7, alter: -1 }: C is b7 in D
const chord = parseChord("Bm7(b5)");
if (chord.ok) chord.value.pitches; // ["B", "D", "F", "A"]
if (chord.ok) chord.value.harte; // "B:hdim7"
harteToBarmark("A:sus4(b7,9)"); // "A9sus4"
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
Several parts
part: Gtr = Electric Guitar 1
part: Pno = Piano
Gtr | G | C | G | D |
Pno | G/B | C | Em | D |
| C | G | D | G |
A chart with several part: lines writes systems (grammar 7.4):
labelled lines that share bars, one per part. A part missing from a
system is tacet there; an unlabelled line is tutti, played by every part.
const chart = parseChart(text);
chart.bars[0].parts; // [{ line, slots, words? }, …] per part, in score order; null where tacet
chart.bars[0].slots; // the first part's slots (N.C., with tacet: true, where it is tacet)
extractPart(text, "Pno"); // one part as a single-part ChartParse, or null
printPart(text, "Pno"); // the same as text: tacet bars written N.C.
projectPart(chart.lines, chart.parts, "Pno"); // one part's lines
A part can also write up to four lines that play together, a pianist's two hands (grammar 7.6), and name its instrument and clef (7.3):
part: Pno = Piano, instrument: piano
part: Bs = Bass, instrument: electric bass
Pno.RH | +G{B3 D4 G4} | *C{C4 E4 G4} |
Pno.LH | {G2}._{D3} / | {C3} |
Bs | {G1} | {C2} |
The first line in a system carries the chord symbols, the others note
sets only. + presses the sustain pedal and * lifts it (2.9);
{G2}._{D3} is a dotted eighth and a sixteenth (2.2).
chart.bars[0].parts[0].lines; // [{ name: "RH", line, slots }, { name: "LH", … }]
extractPart(text, "Pno", "LH"); // one line alone, resting where it isn't written
pedalStates(chart.bars); // whether the pedal is down after each slot
printChart sorts a system into score order and lines up its pipes.
chart.part still gives the one part of a single-part chart, and is
deprecated in favour of parts.
Voice and lyrics
part: Vox = Voice, instrument: voice
key: G, time: 3/4
Vox | [1/4] N.C. | G | G / G7 |
Vox.Mel | [1/4] {D4}:A- | {G4}:maz- / {B4}:ing_{G4}:/ | {B4}:grace / {A4}:how |
lyrics 2: | 'Twas | grace / that | taught / my |
A lead sheet puts the chords on the voice part's bare line and its melody
on a second line, Vox.Mel (grammar 7.6). A syllable follows a note
after a colon ({G4}:maz-; a trailing - continues the word, ~ joins
elided syllables, :/ holds the syllable over a new note). A lyric
row (lyrics:, or lyrics N: for verse N; grammar 7.7) writes later
verses under a system, one cell per bar. --- on a line of its own
separates blocks, and a text line that starts with \ is text.
chart.bars[0].lyrics; // a PlayedLyrics per verse the bar sings: { verse, part?, syllables }
chart.parts[0].sings; // the name of the line whose notes carry the words ("Mel" here; "" for a bare line)
Verses come out in play order: inside a repeat, verse N is pass N.
parseChartnever throws. A line with an error is left out of the play order and reported, and the rest of the chart still reads.printChartchanges spelling and layout only: lines with errors and lyrics print exactly as written.printParseddoes the same from an existingparseChartresult, for a caller that needs both.transposeChartmoves every chord root, slash bass, note set andkey:line, and never the words. Chords are spelled by their interval from the chart's first key, so each keeps its place in the key: C in D becomes Db in Eb, not C#. Given semitones, the new key takes the signature with fewer accidentals (Eb, not D#; F# wins the tie with Gb). A chart with nokey:spells roots C C# D Eb E F F# G Ab A Bb B. Lines with errors stay as written, with a warning. The output is canonical.degreeOfgives a root's degree above a key's tonic, against the major scale for every mode: in A minor, C is b3.- Harte labels (Harte et al., 2005) convert both ways. Every label in the McGill Billboard and Isophonics Beatles datasets converts to Barmark with exactly the same notes.
The parse result, and storing charts
parseChart returns plain data: no classes, Maps or functions, so
JSON.stringify and JSON.parse give an equal object back. Inside one
parse, objects are shared (a bar in bars is the same object as in
events, and a % bar shares its slots), so treat a parse as read-only;
structuredClone(chart) gives a copy to change. Two parses never share
an object. It has two kinds of field:
- The chart as written:
title,parts,creditsandlines, one entry per source line in order (the title, a bar line, a heading, a directive, apart:line, a credit, a lyric row, text, a break, or an invalid bar line kept as written), each with its line number. A bar line, and an invalid one, carriesfirstWritten: the written number of its first bar (0 for a pickup), played or not; absent on a line that writes no bar, and on a line of a system whose bars the numbering does not count (a one-line system whose line is dropped, say), and on a line past a part's share of the lines in a very long chart of many parts (the grammar's A.7 row lists every case). A pickup's line hasfirstWritten: 0, which is falsy: test it with!== undefined. A section heading carriespageShiftwhen a replay that plays comes before it, or is it: add it to thefirstWrittenof the bar lines drawn under that heading (for a replay, its section's) to number the bars down the page, a replayed section counted as written again there. It is absent when 0, and on a heading with no bar line drawn under it, so a chart with no replay that plays has none. - The chart as played, worked out from the written lines:
eventsis play order with fermatas and an open repeat kept as events.barsis the same flattened to onePlayedBarper measure played, repeats, endings, jumps and replays spelled out. A bar'sindexis its position in play order, not a bar number;writtenis the number a band reads on the page, the same on every pass. A pickup (grammar 2.4: a short first bar before a full one) is bar 0, andpickupsays the chart has one; otherwise bars count from 1. Each bar carries its slots, section, key, meter, tempo, feel and, when sung, each verse's syllables (lyrics).sectionsis each section as played, with its first and last bar andform(which distinct section it is; replays share their section's number).
diagnostics: every error and warning, with its line.parseChartnever throws; a chart with errors still parses what it can.
The parse is tens to hundreds of times the size of the text, a few
kilobytes for each bar played: a 700-byte song whose repeats and replays
play out parses to about 170 KB of JSON. Its shape follows this
package's minor versions: 0.17.0, for example, added the break and
lyrics line kinds. So:
- Store the text. It is the stable format: the grammar defines it,
printChartgives it one canonical spelling, and re-parsing an old chart with a newerbarmarkgives the current shape. - Treat a stored parse as a cache, tagged with the
barmarkversion that made it, and parse again when the version changes. - To check a chart before storing it, parse it and look for
diagnostics with
severity: "error"; storeprintChart(text)to keep one spelling of each chart. - Times in a recording belong beside the chart, not in it: key them
by
PlayedBar.index, the play position (not the bar number, which iswritten), which names the same bar however the chart is reformatted or its repeats are spelled (|: :|orx2), until the music itself changes. An open repeat (x ...) plays its bars once inbars, so its later passes have no index of their own.
The key from the chords
keyFromChart reads a chart's key from its chords, keyFromChords does
the same for timed chords from anywhere, and keyFromLabels for a chord
detector's output as it comes:
import { KEY_SURE, keyFromChart, keyFromLabels, parseChart } from "barmark";
const read = keyFromChart(parseChart("tempo: 96\n| G | G | C | D |\n"));
read.home; // { tonic: "G", mode: "major" }: one key for the whole chart
read.homeMargin; // 0.25: at or over KEY_SURE (0.1), a clear read
read.homeRunnerUp; // { tonic: "E", mode: "minor" }: the key it could be taken for
read.keys; // [{ bar: 1, key: G major, margin: 0.25, runnerUp: E minor }]
read.margin; // 0.25: the least certain of `keys`
// A detector's runs: Harte labels, counted in its frames of 2048 samples at 22050 Hz.
const runs = [
{ label: "A:min7", start: 0, end: 129 },
{ label: "D:min", start: 129, end: 194 },
{ label: "E:7", start: 194, end: 258 },
{ label: "N", start: 258, end: 270 },
{ label: "A:min", start: 270, end: 388 },
];
const heard = keyFromLabels(runs, { step: 2048 / 22050 });
heard.home; // { tonic: "A", mode: "minor" }
heard.keys[0].start; // 0, in seconds
keyFromLabels is keyFromChords with the adapter a host would write:
it reads each label with parseHarte, as written, drops N (no chord),
X (unknown) and anything parseHarte does not read, and multiplies a run's start and
end by step, so with the seconds in a frame as step every time in
and out (duration, window, a key's start) is in seconds. Leave
step out for runs already in seconds. keyFromChords takes the chords
themselves, { chord, start, end }, where chord is what parseChord
or parseHarte returns.
Each ten-second window scores the 24 major and minor keys by the chord
time whose triad lies in the key's scale (a minor key also takes its
major V, and the tonic triad counts half as much again); the best path
through the windows, with a cost for each change of key, gives the keys
the music moves through. keys has one entry for music that stays put
and one more for each change that lasts; it is empty when there are no
chords. Neither function throws.
home is the one key to show for a song: of keys, the one the
music is in for the most chord time, every stretch of it counted, and
the earlier of two held as long. keys[0] is the key the music opens
in, which an intro can set; a shorter intro, or a last chorus a step up,
does not move home. It is the key held longest, not for more than
half: of three keys held 40, 30 and 30 seconds it is the first. Chord
time is counted window by window, as the keys are read, and chords that
sound together each count. It is null when there are no chords.
homeMargin says how sure home is, and homeRunnerUp what it
could be mistaken for. The margin is how far home stands clear of
the next best key over all the chord time it is held for, every stretch
together, as a share of that time; the runner-up is that next key, most
often the relative or the parallel. Hold homeMargin against
KEY_SURE when home is the answer you show, and offer the runner-up
when it falls short: "G major, or E minor". Each entry of keys carries
the same pair for its own stretch, margin and runnerUp. A margin is
never under 0: at 0 the runner-up fits those chords as well as the key,
or better.
home, its margin and the runner-ups are barmark's own additions. The
bench measured the opening key, and margin, below, speaks for the
least certain of all the keys read: a clear home after an unsure
intro has a low margin and a high homeMargin. KEY_SURE was
measured on margin; for homeMargin it is the same arithmetic on the
home key's chords, not a figure the bench has checked.
This is Stem Shovel's rule, and keyFromChords is held to the app's own
code case for case. stem-bench
measured that rule on a chord model's reading of recordings (Study 53,
2026-11-30): the opening key right on 47 of 49 songs and 44 of 48
art-song recordings, against 41 and 28 for pitch-class profiles on the
audio, which name the fifth's key when a voice rests on the fifth. A
language model asked about the same chords did no better.
margin says how sure the whole read is: how far the least certain
key stands clear of the next best on the same chords, as a share of the
chord time, which is the least of the keys' own margins. At KEY_SURE (0.1) or more the bench found the rule right
97 times in 100. Under it, show the key as a suggestion. What the rule
gets wrong is kept as the app has it, so the bench's numbers hold:
- A tie goes to the first key in the order C major, C minor, C♯ major and so on. I, IV, V and vi held alike fit a key and its relative equally, at margin 0.
- Chords with no third place no key. A chart written in power chords or suspended chords fits several keys alike: expect a margin near 0.
- A first window in another key is reported as the opening key: an
intro on the parallel major of a minor song, say. For the song's key
take
home, notkeys[0]. - Most of its misses on recordings are the parallel key (major for minor on the same tonic).
keyFromChart times the chart's play order in seconds by its tempo (120
where it gives none; a rit. or accel. is not followed), so its windows
are the ten seconds that were measured. A repeat counts each time it is
played, a hold keeps the chord before it sounding, and N.C., silence,
an unknown slot and a note set count for nothing. In a chart of several
parts the harmony is the first part's that writes a chord symbol, read
throughout. The chart's own key: line is not consulted, so the two can
be compared. A key starts at bar, the PlayedBar.index of the bar its
window starts in. The window, the cost of a change and the tonic's bonus
are options (KeyOptions), and for keyFromChords the music's length,
past which chords are not read.
A chord is counted by the triad its notes make, not by how its name is spelled, so a power chord is its root and fifth. Both functions take time linear in the chords they are given: music long enough for more than 65,536 windows, or chords that overlap for hours, are read in proportionally longer windows, and a chart is read as far as its first quarter of a million played slots.
Develop
bun install
bun test # the test suite
bun run check # Biome and the TypeScript typecheck
bun run fallow # dead code, duplication and complexity (Fallow)
bun run verify:package # build, check the npm package, import it in Node
CI runs these on every push and pull request. Releases follow RELEASING.md; changes are in CHANGELOG.md, and lessons learned along the way are in FINDINGS.md. The project's founding brief, prior art and roadmap are in BRIEF.md.
License
The code is MIT (LICENSE). The grammar specification will be published under CC-BY 4.0.