All files / Bandstand/src/lib chordpro.ts

96.53% Statements 529/548
87.4% Branches 229/262
90.62% Functions 29/32
96.53% Lines 529/548

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724                                                                                      2x     2x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x           477x 477x 477x 477x   2x     2x 398x 398x 398x     2x         2x 112x 112x 112x 98x 98x   100x 100x 100x 100x 100x 100x 100x 227x 227x 227x 227x 227x 227x 100x 100x 100x 100x   2x 56x 56x 56x   56x 106x 106x 106x 106x 106x   56x 468x 468x 468x 225x 225x 225x 225x   90x 90x 90x 90x 90x 90x 216x 90x 90x 90x 201x     4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 187x 1x 1x 1x 1x 146x 14x   40x 40x     243x 468x   55x 55x 55x 468x 12x 12x 12x 468x 76x 76x 76x 467x 100x 100x   56x 56x 56x 56x 56x 56x   5x 5x 5x           2x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   213x 213x 213x 213x   29x 29x 29x 29x 29x 29x   2x 29x 29x 29x 29x 29x 29x 29x 29x 28x 29x 27x 27x 27x 27x 27x 29x 29x   29x   228x 228x 228x   2x 178x 178x 178x 178x 178x 178x 178x 178x     2x 56x 53x 56x 53x 52x 50x 50x 50x 3x 3x   2x 3x 3x 3x 3x 3x   2x 10x 10x 4x 10x 10x 10x 10x 10x 10x 9x 9x 9x 8x   8x 8x 8x 21x 21x 19x 2x 8x 8x 9x 10x 10x 10x             2x 12x 12x 12x 12x 12x 23x 21x 21x 21x 23x 23x 12x 12x 12x 12x 12x   2x 7x 7x 9x 9x 9x 9x   9x 7x 7x 7x           2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x           2x 2x   2x   102x 102x 99x 102x 227x 227x 227x     64x 9x     64x   64x 62x 227x 41x 41x     6x 6x 6x 6x 6x 20x 20x 20x 6x 6x 6x       2x 2x   2x 2x     2x 102x 102x 102x 102x 102x 102x 102x 102x 15x 102x 1x 1x 86x 10x 86x 7x 86x 79x 79x   22x 22x 102x 1x 1x 1x 22x 22x 102x 16x 22x 22x 22x 22x 22x 22x   26x 26x 11x 11x 11x 11x 11x 11x   2x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 4x 4x     2x 23x   23x 23x 23x 23x 86x 86x 86x 23x 23x           2x 17x 17x 16x 16x 16x 17x 24x 24x 24x 24x 16x 16x                     2x 39x 39x 39x 39x 39x 39x 39x 39x 110x     110x           56x 110x 56x 110x 39x 39x 39x 39x 110x 110x 110x 39x 39x   2x 2x     2x       56x 56x 56x 52x 52x 52x 52x     52x 52x   11x 11x 52x 52x     26x 4x 56x 56x 56x                             312x 312x 312x 312x 312x                 2x 10x 10x 10x 10x 10x 10x 10x 10x 10x   10x   10x 10x 10x 32x 32x 32x   10x 55x 55x 55x   36x 55x 20x 20x 20x 20x 20x 20x 20x 20x 20x   55x   2x 2x 2x 2x 8x 2x 7x 7x 7x 2x 2x 2x 2x   55x 13x 13x 13x 13x 10x 10x 13x 10x 10x 13x 3x 3x 13x 13x 1x 1x 10x   10x 10x 10x  
/**
 * A small ChordPro reader, transposer and importer.
 *
 * Charts are stored as ChordPro text: `Oh, I could [G]hide 'neath the [Am]wings`
 * with `{start_of_verse: Verse 1}` … `{end_of_verse}` around each section.
 * Everything the app shows (chart view, performance mode, PDFs, history diffs)
 * is derived from that one source, so there is nothing to keep in sync.
 *
 * Only the subset of ChordPro the band uses is understood; unknown directives
 * are kept in `meta` and otherwise ignored rather than rejected.
 */
 
export type Segment = {chord: string | null; lyric: string}
 
export type ChartLine =
  | {kind: 'lyrics'; segments: Segment[]}
  | {kind: 'comment'; text: string}
  /** Guitar tablature: shown verbatim in a monospace font */
  | {kind: 'tab'; text: string}
 
export type Section = {
  /** verse | chorus | bridge | intro | interlude | outro | solo | part … */
  type: string
  label: string
  /** Parenthesised remark after the label, e.g. "x2, 2nd time fade out" */
  note: string
  lines: ChartLine[]
  /**
   * Music notation, for a {start_of_abc} section: ABC text, drawn as a
   * staff. It is written in the chart's original key; `abcSteps` is how far
   * the chart has been transposed since, which the notation follows.
   */
  abc?: string
  abcSteps?: number
}
 
export type Chart = {
  title: string
  key: string | null
  meta: Record<string, string>
  sections: Section[]
}
 
const DIRECTIVE = /^\{\s*([\w-]+)\s*(?::\s*(.*?))?\s*\}$/
// Root, quality, optional slash bass. The quality is restricted to chord
// vocabulary so that words like "Chorus" or "Bridge" are not read as chords.
const CHORD =
  /^([A-G](?:#|b)?)((?:maj|min|dim|aug|sus|add|m|M|[0-9]|[#b+\-°ø()])*)(?:\/([A-G](?:#|b)?))?$/
 
const ALIASES: Record<string, string> = {
  t: 'title',
  st: 'subtitle',
  c: 'comment',
  ci: 'comment',
  comment_italic: 'comment',
  soc: 'start_of_chorus',
  eoc: 'end_of_chorus',
  sov: 'start_of_verse',
  eov: 'end_of_verse',
  sob: 'start_of_bridge',
  eob: 'end_of_bridge',
}
 
/**
 * Peel wrapping off a chord token: "(B)", "(C" and "G)," are chords inside
 * a parenthesised group or followed by punctuation.
 */
function unwrap(token: string) {
  const m = token.match(/^(\(?)(.*?)([),.]*)$/)!
  return {pre: m[1], core: m[2], post: m[3]}
}
 
const BASS_ONLY = /^\/([A-G](?:#|b)?)$/
 
/** A chord, possibly parenthesised, or a bass-only change like "/G". */
export function isChord(token: string): boolean {
  const {core} = unwrap(token)
  return CHORD.test(core) || BASS_ONLY.test(core)
}
 
/** Repeat counts, no-chord and bar lines: chord-row markings, not chords. */
export function isChordMarking(token: string): boolean {
  return /^\(?x\d+\)?$/i.test(token) || /^(N\.?C\.?|\|+|%|-)$/i.test(token)
}
 
/** Split "Chorus (x2, fade)" into label "Chorus" and note "x2, fade". */
export function splitLabel(raw: string): {label: string; note: string} {
  const text = raw.replace(/^label="(.*)"$/, '$1').trim()
  const m = text.match(/^(.*?)\s*\((.*)\)\s*$/)
  if (m && m[1]) return {label: m[1].trim(), note: m[2].trim()}
  return {label: text, note: ''}
}
 
function parseLyricLine(line: string): ChartLine {
  const segments: Segment[] = []
  const re = /\[([^\]]*)\]/g
  let last = 0
  let pending: string | null = null
  let m: RegExpExecArray | null
  while ((m = re.exec(line))) {
    const before = line.slice(last, m.index)
    if (before || pending !== null)
      segments.push({chord: pending, lyric: before})
    pending = m[1]
    last = m.index + m[0].length
  }
  const rest = line.slice(last)
  if (rest || pending !== null) segments.push({chord: pending, lyric: rest})
  return {kind: 'lyrics', segments}
}
 
export function parseChordPro(source: string): Chart {
  const chart: Chart = {title: '', key: null, meta: {}, sections: []}
  let current: Section | null = null
  let implicit = false
 
  const open = (type: string, rawLabel: string, isImplicit = false) => {
    const {label, note} = splitLabel(rawLabel)
    current = {type, label, note, lines: []}
    chart.sections.push(current)
    implicit = isImplicit
  }
 
  for (const rawLine of source.replace(/\r\n?/g, '\n').split('\n')) {
    const line = rawLine.replace(/\s+$/, '')
    const d = line.trim().match(DIRECTIVE)
    if (d) {
      const name = ALIASES[d[1].toLowerCase()] ?? d[1].toLowerCase()
      const value = d[2] ?? ''
      const start = name.match(/^start_of_(\w+)$/)
      if (start) {
        // Notation and tab have no heading unless given one ("Horn riff")
        open(
          start[1],
          value || (['abc', 'tab'].includes(start[1]) ? '' : cap(start[1])),
        )
        continue
      }
      if (/^end_of_\w+$/.test(name)) {
        current = null
        continue
      }
      if (name === 'chorus') {
        // A bare {chorus} repeats the most recent chorus. It is written out
        // in full: charts are read mid-song, so never "same as above".
        const prev = [...chart.sections]
          .reverse()
          .find((s) => s.type === 'chorus')
        const {label, note} = splitLabel(value || prev?.label || 'Chorus')
        chart.sections.push({
          type: 'chorus',
          label,
          note,
          lines: structuredClone(prev?.lines ?? []),
        })
        current = null
        continue
      }
      if (name === 'comment') {
        if (!current) open('part', '', true)
        current!.lines.push({kind: 'comment', text: value})
        continue
      }
      if (name === 'title') chart.title = value
      else if (name === 'key') chart.key = value || null
      else chart.meta[name] = value
      continue
    }
 
    // (TS narrows `current` to null here because it is assigned in a closure)
    const cur = current as Section | null
    if (cur?.type === 'abc') {
      // Kept verbatim, blank lines and all: it's another language
      cur.abc = cur.abc === undefined ? rawLine : `${cur.abc}\n${rawLine}`
      continue
    }
    if (cur?.type === 'tab') {
      if (line.trim()) cur.lines.push({kind: 'tab', text: line})
      continue
    }
    if (!line.trim()) {
      if (implicit) current = null
      continue
    }
    if (!current) open('part', '', true)
    current!.lines.push(parseLyricLine(line))
  }
 
  for (const s of chart.sections) if (s.abc !== undefined) s.abc = s.abc.trim()
  chart.sections = chart.sections.filter(
    (s) => s.lines.length > 0 || s.label || s.abc,
  )
  return chart
}
 
function cap(s: string) {
  return s.charAt(0).toUpperCase() + s.slice(1)
}
 
// ---------------------------------------------------------------------------
// Transposition
// ---------------------------------------------------------------------------
 
const SHARPS = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
const FLATS = ['C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B']
// How each key is conventionally spelled; also decides sharps vs flats.
const MAJOR_KEYS = [
  'C',
  'Db',
  'D',
  'Eb',
  'E',
  'F',
  'F#',
  'G',
  'Ab',
  'A',
  'Bb',
  'B',
]
const MINOR_KEYS = [
  'Cm',
  'C#m',
  'Dm',
  'Ebm',
  'Em',
  'Fm',
  'F#m',
  'Gm',
  'G#m',
  'Am',
  'Bbm',
  'Bm',
]
const FLAT_KEYS = new Set([
  'F',
  'Bb',
  'Eb',
  'Ab',
  'Db',
  'Gb',
  'Dm',
  'Gm',
  'Cm',
  'Fm',
  'Bbm',
  'Ebm',
])
 
function noteIndex(note: string): number {
  const i = SHARPS.indexOf(note)
  return i >= 0 ? i : FLATS.indexOf(note)
}
 
function shift(note: string, semitones: number, flats: boolean): string {
  const i = noteIndex(note)
  if (i < 0) return note
  const j = (((i + semitones) % 12) + 12) % 12
  return (flats ? FLATS : SHARPS)[j]
}
 
export function transposeChord(
  chord: string,
  semitones: number,
  flats = false,
): string {
  if (semitones % 12 === 0) return chord
  const {pre, core, post} = unwrap(chord)
  const b = core.match(BASS_ONLY)
  if (b) return pre + '/' + shift(b[1], semitones, flats) + post
  const m = core.match(CHORD)
  if (!m) return chord
  const [, root, quality, bass] = m
  return (
    pre +
    shift(root, semitones, flats) +
    quality +
    (bass ? '/' + shift(bass, semitones, flats) : '') +
    post
  )
}
 
function isMinorQuality(quality: string) {
  return /^m(?!aj)/.test(quality)
}
 
export function transposeKey(key: string, semitones: number): string {
  const m = key.match(CHORD)
  if (!m) return key
  const minor = isMinorQuality(m[2])
  const i = noteIndex(m[1])
  if (i < 0) return key
  const j = (((i + semitones) % 12) + 12) % 12
  return (minor ? MINOR_KEYS : MAJOR_KEYS)[j]
}
 
/** The key: the {key} directive if set, else the first chord of the song. */
export function detectKey(chart: Chart): string | null {
  if (chart.key) return chart.key
  for (const s of chart.sections)
    for (const l of s.lines)
      if (l.kind === 'lyrics')
        for (const seg of l.segments) {
          const m = seg.chord ? unwrap(seg.chord).core.match(CHORD) : null
          if (m) return m[1] + (isMinorQuality(m[2]) ? 'm' : '')
        }
  return null
}
 
export function semitonesBetween(from: string, to: string): number {
  const a = noteIndex(from.match(CHORD)?.[1] ?? '')
  const b = noteIndex(to.match(CHORD)?.[1] ?? '')
  if (a < 0 || b < 0) return 0
  return (((b - a) % 12) + 12) % 12
}
 
export function transposeChart(chart: Chart, semitones: number): Chart {
  const steps = ((semitones % 12) + 12) % 12
  if (steps === 0) return chart
  const fromKey = detectKey(chart)
  const toKey = fromKey ? transposeKey(fromKey, steps) : null
  const flats = toKey ? FLAT_KEYS.has(toKey) : false
  return {
    ...chart,
    key: chart.key ? toKey : chart.key,
    sections: chart.sections.map((s) => ({
      ...s,
      ...(s.abc ? {abcSteps: (s.abcSteps ?? 0) + steps} : {}),
      lines: s.lines.map((l) =>
        l.kind !== 'lyrics'
          ? l
          : {
              kind: 'lyrics',
              segments: l.segments.map((seg) => ({
                ...seg,
                chord: seg.chord
                  ? transposeChord(seg.chord, steps, flats)
                  : null,
              })),
            },
      ),
    })),
  }
}
 
// ---------------------------------------------------------------------------
// Plain text (chords over words) — used for history diffs and imports
// ---------------------------------------------------------------------------
 
/** Render one lyric line as a chord line above a lyric line, column-aligned. */
export function lineToChordsOverWords(line: ChartLine): string[] {
  if (line.kind === 'comment') return [`(${line.text})`]
  if (line.kind === 'tab') return [line.text]
  let chords = ''
  let words = ''
  for (const seg of line.segments) {
    if (seg.chord !== null) {
      if (chords.length > words.length) words = words.padEnd(chords.length)
      chords = chords.padEnd(words.length) + seg.chord + ' '
    }
    words += seg.lyric
  }
  const out: string[] = []
  if (chords.trim()) out.push(chords.trimEnd())
  if (words.trim()) out.push(words.trimEnd())
  return out
}
 
export function chartToChordsOverWords(chart: Chart): string {
  const out: string[] = []
  chart.sections.forEach((s, i) => {
    if (i > 0) out.push('')
    const head = s.label || (s.abc ? 'Notation' : cap(s.type))
    out.push(`[${head}]${s.note ? ` (${s.note})` : ''}`)
    for (const l of s.lines) out.push(...lineToChordsOverWords(l))
    // Notation shows as its ABC text, so a history diff shows what changed
    if (s.abc) out.push(...s.abc.split('\n'))
  })
  return out.join('\n')
}
 
// ---------------------------------------------------------------------------
// Import: chords-over-words text (the old Google Docs) → ChordPro
// ---------------------------------------------------------------------------
 
const NON_CHORD_TOKENS = new Set([
  '|',
  '||',
  '-',
  '/',
  '%',
  'N.C.',
  'NC',
  '(',
  ')',
])
 
/** "(x2)", "x4", "F(x2)" → the repeat part, if the token is one */
const REPEAT = /^\(?x\d+\)?$/i
 
/**
 * A remark written into a chord line: "[hold 4 bars]" or "(organ fill)" --
 * anything bracketed or parenthesised that is not itself a chord group.
 */
const REMARK =
  /\[[^\]]*\]|\((?![A-G][#b]?[^\s)]*(?:\)|\s))(?!x\d)(?:[^()]|\([^()]*\))*\)/g
 
export function isChordLine(line: string): boolean {
  // Remarks don't disqualify a chord line; they are kept as notes
  const tokens = line.replace(REMARK, ' ').trim().split(/\s+/).filter(Boolean)
  if (!tokens.length) return false
  let chords = 0
  for (const t of tokens) {
    const bare = t.replace(/^\(|\)$/g, '')
    const glued = t.match(/^(.+?)(\(x\d+\))$/i)
    if (isChord(tidyChord(bare)) || (glued && isChord(glued[1]))) chords++
    // "C-Bb-G": quick changes within a bar ("rest-B-C-C#-D" a walk)
    else if (
      /-/.test(bare) &&
      bare.split('-').every((c) => isChord(c) || /^rest$/i.test(c)) &&
      bare.split('-').some((c) => isChord(c))
    )
      chords++
    // "////" and "--": beats and holds; "Pause", "rest", "stop": silences
    else if (/^(\/+\.?|-+|pause|rest|stop|hold)$/i.test(t)) continue
    else if (!NON_CHORD_TOKENS.has(t) && !REPEAT.test(t)) return false
  }
  return chords > 0
}
 
/** "C F Bb F (x4)" → "[C] [F] [Bb] [F] (x4)": chords become chords, the rest stays text. */
function inlineChords(text: string): string {
  return text
    .trim()
    .split(/\s+/)
    .map((t) => {
      const glued = t.match(/^(.+?)(\(x\d+\))$/i)
      if (glued && isChord(glued[1])) return `[${glued[1]}]${glued[2]}`
      return isChord(t) ? `[${t}]` : t
    })
    .join(' ')
}
 
/** A tablature string line: `e|---7---5p4p0---|` */
// "e|---7---5p4p0---|", or a bare tab staff line "-9-7---4-2----|"
export const TAB_LINE =
  /^\s*(?:[A-Ga-g]\|[-0-9a-z|~/\\^().*\s]*|[-0-9hpbr/\\~x|.]*-{6,}[-0-9hpbr/\\~x|.]*)$/
 
const SECTION_WORDS =
  /^(intro|verse|pre-?chorus|chorus|bridge|interlude|instrumental|solo|outro|coda|ending|tag|refrain|break)\b/i
 
/** Recognise a section header line and split it into label, note and any chords that follow. */
export function parseHeader(
  line: string,
): {label: string; note: string; chords: string} | null {
  let label: string
  let rest: string
  const bracket = line.match(/^\[([^\]]+)\]\s*(.*)$/)
  const numbered = line.match(/^#\s*(\d+)\.?\s*$/)
  const colon = line.match(/^([A-Za-z][A-Za-z0-9 '&/.-]{0,30}?)\s*:\s*(.*)$/)
  if (bracket && !isChord(bracket[1])) {
    ;[label, rest] = [bracket[1], bracket[2]]
  } else if (numbered) {
    return {label: `Verse ${numbered[1]}`, note: '', chords: ''}
  } else if (
    colon &&
    (colon[1] === colon[1].toUpperCase() || SECTION_WORDS.test(colon[1]))
  ) {
    ;[label, rest] = [colon[1], colon[2]]
  } else {
    return null
  }
 
  const notes: string[] = []
  const dash = label.match(/^(.*?)\s+-\s+(.*)$/)
  if (dash) {
    label = dash[1]
    notes.push(dash[2])
  }
  rest = rest.trim()
  let chords = ''
  if (rest && isChordLine(rest)) chords = inlineChords(rest)
  else if (rest) notes.push(rest.replace(/^[-–]\s*|:$|^\(|\)$/g, '').trim())
  return {
    label: titleCase(label),
    note: notes.filter(Boolean).map(titleCase).join('; '),
    chords,
  }
}
 
function titleCase(s: string): string {
  if (s !== s.toUpperCase()) return s.trim()
  return s
    .toLowerCase()
    .replace(/\b([a-z])/g, (c) => c.toUpperCase())
    .replace(/\b(\d+)X\b/gi, '$1x')
    .trim()
}
 
export function sectionType(name: string): string {
  const n = name.toLowerCase()
  if (/pre-?chorus/.test(n)) return 'prechorus'
  for (const t of [
    'chorus',
    'verse',
    'bridge',
    'intro',
    'interlude',
    'outro',
    'solo',
  ])
    if (n.includes(t)) return t
  if (/instrumental|break/.test(n)) return 'solo'
  if (/coda|ending/.test(n)) return 'outro'
  return 'part'
}
 
/** Insert `[chord]` markers from a chord line into the lyric line below it. */
export function mergeChordLine(chordLine: string, lyricLine: string): string {
  const marks: {col: number; chord: string}[] = []
  // A remark is one token, re-wrapped in parentheses so it can't nest brackets
  const re = new RegExp(`${REMARK.source}|\\S+`, 'g')
  let m: RegExpExecArray | null
  while ((m = re.exec(chordLine)))
    marks.push({
      col: m.index,
      chord: m[0].startsWith('[') ? `(${m[0].slice(1, -1)})` : tidyChord(m[0]),
    })
  return placeChords(lyricLine, marks)
}
 
/**
 * A line with its chords typed in ("n[Cm7]ight", "Hi-de[Em]-hi"), with
 * each chord moved onto a syllable the way placeChords does.
 */
export function placeInlineChords(line: string): string {
  if (!/\[/.test(line) || !/[A-Za-z]/.test(line.replace(/\[[^\]]*\]/g, '')))
    return line
  const marks: {col: number; chord: string}[] = []
  let lyric = ''
  let at = 0
  for (const m of line.matchAll(/\[([^\]]*)\]/g)) {
    lyric += line.slice(at, m.index)
    at = m.index! + m[0].length
    marks.push({col: lyric.length, chord: m[1]})
  }
  return placeChords(lyric + line.slice(at), marks)
}
 
/**
 * Chords onto words at the columns they were typed. A chord can sit mid-word
 * on a syllable ("repu[Cm7]tation", "a[E]gain"); one that splits a word
 * where no syllable starts ("n[Cm7]ight", "bou[D7]rbon": a syllable starts
 * with a consonant and its vowel, after a vowel earlier in the word) was typed a letter or two off, and goes to the
 * word's start. One over a gap goes to the word just after it. Several on one
 * word ("G - E7" over "scotch,") are quick changes: the first starts it, the
 * rest wait just after it.
 */
export function placeChords(
  lyricLine: string,
  marks: {col: number; chord: string}[],
): string {
  let lyric = lyricLine
  const width = marks.length ? marks[marks.length - 1].col : 0
  if (lyric.length < width) lyric = lyric.padEnd(width)
  let prev = -1
  for (const mark of marks) {
    if (!lyricLine.trim() || mark.col >= lyricLine.length) continue
    // A hold mark or beat slash takes no word: at a word's start it stays,
    // inside one it waits just after it
    if (/^[-/|.]+$/.test(mark.chord)) {
      const start = snapToSyllable(lyricLine, mark.col)
      if (start !== mark.col && WORD_CHAR.test(lyricLine[mark.col] ?? ''))
        mark.col = wordEnd(lyricLine, start)
      continue
    }
    const at = snapToSyllable(lyricLine, mark.col)
    if (at <= prev) mark.col = wordEnd(lyricLine, prev)
    else mark.col = prev = at
  }
  const ordered = marks
    .map((m, i) => ({...m, i}))
    .sort((a, b) => a.col - b.col || a.i - b.i)
  for (let i = ordered.length - 1; i >= 0; i--) {
    const {col, chord} = ordered[i]
    lyric = lyric.slice(0, col) + `[${chord}]` + lyric.slice(col)
  }
  return lyric.replace(/\s+$/, '')
}
 
const WORD_CHAR = /[A-Za-z0-9'’/]/
const VOWEL = /[aeiouy]/i
 
/** Where a chord typed at `col` belongs: on its syllable, or the word's start. */
export function snapToWord(lyric: string, col: number) {
  return snapToSyllable(lyric, col)
}
 
function snapToSyllable(lyric: string, col: number) {
  if (col >= lyric.length) return col
  if (WORD_CHAR.test(lyric[col])) {
    let s = col
    while (s > 0 && WORD_CHAR.test(lyric[s - 1])) s--
    let e = col
    while (e < lyric.length && WORD_CHAR.test(lyric[e])) e++
    // A syllable starts with a consonant and its vowel ("repu|tation",
    // "a|gain"), after a vowel earlier in the word
    const syllable =
      VOWEL.test(lyric.slice(s, col)) &&
      // never just after an apostrophe: "we'|ve", "don'|t"
      !/['’]$/.test(lyric.slice(s, col)) &&
      /^[b-df-hj-np-tv-z][aeiouy]/i.test(lyric.slice(col, e))
    return syllable ? col : s
  }
  // Over a space or a hyphen ("Hi-de[Em]-hi"): the next word, if it's
  // close. Before the line's first word a chord keeps its own beat
  if (!lyric.slice(0, col).trim()) return col
  let s = col
  while (s < lyric.length && /[\s-]/.test(lyric[s])) s++
  return s < lyric.length && s - col <= 3 && WORD_CHAR.test(lyric[s]) ? s : col
}
 
/**
 * Just past the word at `start`, and past punctuation that ends it
 * ("scotch,") but not into the next word ("baby.......do").
 */
function wordEnd(lyric: string, start: number) {
  let e = start
  while (e < lyric.length && WORD_CHAR.test(lyric[e])) e++
  let p = e
  while (p < lyric.length && /[^\sA-Za-z0-9'’]/.test(lyric[p])) p++
  return p >= lyric.length || /\s/.test(lyric[p]) ? p : e
}
 
/** "Em." and "C7-" (a chord with a hold mark typed onto it) → "Em", "C7". */
function tidyChord(token: string) {
  if (token === '/.') return '/'
  const bare = token.replace(/[.-]+$/, '')
  return bare !== token && isChord(bare) ? bare : token
}
 
export type ImportResult = {source: string; key: string | null}
 
/**
 * Convert a chords-over-words chart (chord lines above lyric lines) into
 * ChordPro. Understands both header styles in the band's old Docs:
 * `[Verse 1]` / `[Intro] A` and `INTRO: C F Bb F (x4)` / `#1.` / `CHORUS:`.
 */
export function importChordsOverWords(
  text: string,
  title: string,
): ImportResult {
  const lines = text
    .replace(/\r\n?/g, '\n')
    .replace(/ /g, ' ')
    .replace(/\\([[\]])/g, '$1')
    .split('\n')
    .map((l) => l.replace(/\s+$/, ''))
    // Markdown headings (the song title in a Docs export) are not chart content
    .filter((l) => !/^#{1,6}\s/.test(l.trim()))
 
  const out: string[] = [`{title: ${title}}`]
  let openType: string | null = null
  const close = () => {
    if (openType) out.push(`{end_of_${openType}}`)
    openType = null
  }
 
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i]
    const trimmed = line.trim()
    if (!trimmed) continue
 
    const h = parseHeader(trimmed)
    if (h) {
      close()
      openType = sectionType(h.label)
      if (out.length > 1) out.push('')
      out.push(
        `{start_of_${openType}: ${h.label}${h.note ? ` (${h.note})` : ''}}`,
      )
      if (h.chords) out.push(h.chords)
      continue
    }
 
    if (TAB_LINE.test(line)) {
      // Tablature can't live inside a lyric section in ChordPro
      close()
      out.push('{start_of_tab}')
      while (
        i < lines.length &&
        (TAB_LINE.test(lines[i]) || !lines[i].trim())
      ) {
        if (lines[i].trim()) out.push(lines[i])
        i++
      }
      out.push('{end_of_tab}')
      i--
      continue
    }
 
    if (isChordLine(line)) {
      const next = lines[i + 1]
      if (
        next !== undefined &&
        next.trim() &&
        !isChordLine(next) &&
        !parseHeader(next.trim())
      ) {
        out.push(mergeChordLine(line, next))
        i++
      } else {
        out.push(mergeChordLine(line, ''))
      }
      continue
    }
    out.push(line)
  }
  close()
 
  const source = out.join('\n') + '\n'
  return {source, key: detectKey(parseChordPro(source))}
}