Перейти к основному содержанию
Рецепт номер 164

Рецепты · Глава 9 · Полные издания

Песенник: мелодия, слова и аккорды

Каждая песня — блок ABC: мелодия, аккорды над станом и первый куплет под нотами, выгравированные по ширине колонки одним стилем нот.

На этой странице
Вывод
Canvas · PDF
Уровень
Средний
Postext
Проверено с Postext 1.65.0
Требуется ≥ 1.54.0 · postext-pdf ≥ 1.54.0
Лицензия
Обновлено 22 окт. 2026 г.
Код: MIT · Текст: CC BY 4.0

с. 2–3 из 6

  • Образец на английском: русского издания пока нет
  • Обрезной формат 148 × 210 мм
  • 1 колонка
  • Spectral 10,3/14
  • Fraunces
  • Spectral SC
  • 6 страниц
  • Уровень
  • Postext 1.57.1
  • Свёрстано за 212 мс
  • Строк кода: 164

Коротко

Маленький песенник, чтобы петь за столом. Песня записана простым текстом в нотации ABC, а Postext рисует стан, ноты, гитарные аккорды и слова под нотами. Остальные куплеты идут в две колонки.

Что получится

Songs for the Long Table — карманный песенник формата A5: титул цвета марены, обращение к поющим с содержанием, три песни и примечания об их происхождении. Каждая песня открывается крупным номером цвета марены, заглавием Fraunces и строкой об авторах капителью. Ниже мелодия на стане 5,5 мм шрифтом Leland, гитарные аккорды над тактами и первый куплет под нотами гарнитурой Spectral, текстовой в этой книге. Остальные куплеты стоят в две колонки, и поющий читает прямо вниз от последнего такта. У Amazing Grace длинные строки в колонке переносились бы, поэтому её куплеты стоят один под другим, по центру. Испанская версия — песенник ко дню рождения с тремя песнями покороче, по две на страницу.

Рецепт отвечает на вопросы

  • Как набрать песенник с мелодией, словами под нотами и обозначениями аккордов?

Короткий ответ

script.js · строки 33–50в полном коде
// A song is an ```abc fence in the Markdown: the melody, its chords written "G" before the note
// they fall on, and the first verse on a w: line under it. The look is set here, once.
const scoreStyle = {
  staffSize: mm(5.5), // a songbook rastral; the words under it come out at about 8 pt
  musicFont: 'Leland', // lighter noteheads than Bravura, close to Spectral's colour
  textFont: TEXT, // words and chord names in the text face, not the engraver's Times
  spacing: 1, // the engraver's own: five or six bars of 3/4 to a system on this measure
  barNumbers: 'none', // a table of singers counts verses, not bars
  systemGap: mm(4.5), // room for the chord names between one system's words and the next
  marginTop: pt(4),
  marginBottom: pt(LEAD),
  color: col('ink'),
  minSystemsAtBreak: 2, // never a lone system at a page foot or head
};
// Two habits of Verovio's ABC reader shape the w: lines. Every sung note takes the next
// syllable in order: the `_` and `*` holds are read as nothing, so the second note of a
// slurred pair (B/G/ under "-ing") gets a no-break space, which prints nothing. A tied note
// takes none. `~` joins two syllables on one note: "de~a-trás".

Ингредиенты

Шрифты
Spectral, Spectral SC, Fraunces (SIL OFL 1.1)
Материалы
Нет: все иллюстрации рисует код

Порядок работы

#1 · Запишите песню, стиль нот задайте один раз

Стиль нот — это короткий ответ выше. В Markdown каждая песня — блок ```abc: строки заголовка задают размер, длительность и тональность; аккорд в двойных кавычках ("D7"A) печатается над нотой, перед которой стоит; строка w: под музыкой ставит по слогу под каждую ноту, слоги разделены дефисами. Мелодия с запевом и припевом — две строки музыки, у каждой своя w:. Размер стана, нотный шрифт, гарнитура слов, номера тактов и интервал между системами берутся из scoreStyle, поэтому три песни одинаковы, а в блоках одна музыка.

#2 · Откройте каждую песню номером и строкой об авторах

script.js · строки 66–81в полном коде
// # Amazing Grace {credit="Words John Newton, 1779 · Tune New Britain, American, 1835"}
// The songs run on, three lines apart: a short song shares its page with the next one.
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
const text = (id, content, font, size, color, placement, extra = {}) => ({ kind: 'text', id,
  content, fontFamily: font, fontSize: pt(size), color: col(color), align: 'left', placement,
  ...extra });
const songHead = { enabled: true, minHeight: mm(21), slot: { elements: [
  text('number', '{number}', DISPLAY, 26, 'madder', at('container', 'top-left', 0, 1),
    { fontWeight: 600, lineHeight: 1 }),
  text('title', '{titleText}', DISPLAY, 21, 'ink', { ...at('container', 'top-left', 12, 2),
    size: { width: mm(100) } }, { fontWeight: 600, lineHeight: 1.05 }),
  text('credit', '{attr.credit}', LABEL, 8.4, 'madder', { ...at('#title', 'below', 0, 2.2),
    size: { width: mm(100) } }, { fontWeight: 600, letterSpacing: pt(0.6) }),
] } };
const songs = { level: 1, numberingTemplate: '{1}', advancedDesign: songHead,
  marginTop: pt(LEAD * 3), marginBottom: pt(0), breakBefore: { enabled: false } };

Песня — заголовок первого уровня с атрибутом credit, и его оформление собирает из него номер, заглавие и строку об авторах. minHeight даёт каждой песне одинаковую шапку 21 мм, поэтому станы начинаются на одной высоте каждой страницы. Песни идут подряд, с тремя строками интервала над каждым заглавием, и ноты никогда не разрываются раньше второй системы (minSystemsAtBreak: 2): английские песни занимают по странице, а две короткие испанские делят одну.

#3 · Поставьте остальные куплеты в две колонки

script.js · строки 54–62в полном коде
// :::columns{count=2} holds one :::verse block per stanza; each line of the stanza is a
// line of Markdown, the turned lines indented two spaces (one em). A hymn in long lines
// (Amazing Grace) drops the columns: its stanzas stand one under another, centred.
const verse = { id: 'verse', fontSize: pt(9.4), lineHeight: pt(13), hyphenation: false,
  marginBottom: pt(13 / 2) };
const chorus = { id: 'chorus', fontSize: pt(9.4), lineHeight: pt(13), italic: true,
  hyphenation: false, marginBottom: pt(LEAD / 2) };
const colophon = { id: 'colophon', fontFamily: LABEL, fontSize: pt(7.8), lineHeight: pt(11),
  color: col('muted'), textAlign: 'left', firstLineIndent: pt(0), marginTop: pt(LEAD * 2) };

Каждый куплет — блок :::verse: строки разрываются там, где их разорвал поэт, а вторая и четвёртая отступают на один em. Группа :::columns{count=2 gap=4mm} ставит куплеты рядом в 9,4 пт. Сначала посчитайте знаки: строки Бёрнса входят в колонку 55 мм, длинный размер Ньютона нет, поэтому Amazing Grace остаётся одним центрированным блоком :::verse, где куплеты разделены пустыми строками.

#4 · Не нагружайте страницу

script.js · строки 119–131в полном коде
const head = (id, content, parity, edge, x, style = {}) => ({
  kind: 'text', id, content, parity, pages: 'all', // a song's first page carries them too
  fontFamily: LABEL, fontSize: pt(8.4), fontWeight: 600, letterSpacing: pt(0.9),
  color: col('muted'), ...style,
  placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(12.5) } },
});
const folio = { fontFamily: TEXT, fontWeight: 600, letterSpacing: pt(0), color: col('madder') };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', OUTER, folio),
  head('verso-title', '{title}', 'even', 'top-left', OUTER + 8),
  head('recto-song', '{chapterTitle}', 'odd', 'top-right', -(OUTER + 8)),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -OUTER, folio),
] };

Колонтитулы стоят на каждой странице с песнями, заглавие книги на левой и песни на правой, колонцифра цвета марены, как номера песен. Титул и обращение к поющим убирают их пустым header в своих стилях заголовков.

Рецепт целиком

Sandbox
// ═══ Postext Cookbook · Nº 164 · Songbook: melody, words under the notes, chords ═══════
// https://postext.dev/en/cookbook/songbook-melody-words-chords
// Code: MIT · Words and tunes: public domain (see the notes in each edition) · Prose: CC BY 4.0
// Fonts: Spectral, Spectral SC, Fraunces (SIL OFL 1.1); Leland (music) · Needs postext ≥ 1.54.0
import {
  buildDocumentWithFonts, renderPageToCanvas, initMusicEngine,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'songbook-melody-words-chords';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = { // every colour in the config links to one of these
  ink: '#211e1b', // text and notes: a warm near-black
  madder: '#8a3324', // the one accent: song numbers, the title page, credit lines
  tint: '#f1e7d8', // the subtitle on the madder ground (8.2:1)
  rule: '#cbbca6', // hairlines
  muted: '#675e55', // running heads, notes and the colophon (5.9:1 on the paper)
  paper: '#fbf8f1', // a cream stock
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  // The engine's defaults link to 'main-color': point it at the accent, so nothing prints blue.
  { id: 'main-color', name: 'madder (defaults)', value: { hex: palette.madder, model: 'hex' } },
];
const [TEXT, LABEL, DISPLAY] = ['Spectral', 'Spectral SC', 'Fraunces'];
const LEAD = 14; // pt: the body's leading
const OUTER = 15; // mm: the outer margin, where the running heads and folios align

// #region answer: the score style: a 5 mm staff in Leland, the words in the book's face
// A song is an ```abc fence in the Markdown: the melody, its chords written "G" before the note
// they fall on, and the first verse on a w: line under it. The look is set here, once.
const scoreStyle = {
  staffSize: mm(5.5), // a songbook rastral; the words under it come out at about 8 pt
  musicFont: 'Leland', // lighter noteheads than Bravura, close to Spectral's colour
  textFont: TEXT, // words and chord names in the text face, not the engraver's Times
  spacing: 1, // the engraver's own: five or six bars of 3/4 to a system on this measure
  barNumbers: 'none', // a table of singers counts verses, not bars
  systemGap: mm(4.5), // room for the chord names between one system's words and the next
  marginTop: pt(4),
  marginBottom: pt(LEAD),
  color: col('ink'),
  minSystemsAtBreak: 2, // never a lone system at a page foot or head
};
// Two habits of Verovio's ABC reader shape the w: lines. Every sung note takes the next
// syllable in order: the `_` and `*` holds are read as nothing, so the second note of a

Собранный script.js работает как есть: вставьте его в модульный скрипт любой страницы или откройте рецепт на CodePen. Папка рецепта на GitHub ↗ (открывается в новой вкладке)

Варианты

#Гравируйте шрифтом Bravura

У Bravura головки нот тяжелее, и выглядит она как гравированная доска; она подходит сборнику гимнов, набранному более тёмной гарнитурой.

-  musicFont: 'Leland', // lighter noteheads than Bravura, close to Spectral's colour
+  musicFont: 'Bravura',

#Пронумеруйте такты

Хор репетирует по номерам тактов; печатайте номер в начале каждой системы.

-  barNumbers: 'none', // a table of singers counts verses, not bars
+  barNumbers: 'system',

Частые ошибки

Подводный камень

Стиль заголовка наследует разрыв страницы своего уровня

Запись headingStyles берёт каждое пропущенное поле у своего уровня заголовка, в том числе breakBefore. Страница содержания или выходных данных со стилем на H1 после :::pagebreak наследует parity 'odd' и оказывается после пустой страницы. Дайте такому стилю breakBefore: { enabled: false }. Стили заголовков →

  • Читатель ABC в Verovio не понимает знаков удержания _ и * в строке w:: каждая нота берёт следующий слог. Под второй нотой лиги пишите отдельным слогом неразрывный пробел (U+00A0): он ничего не печатает. Залигованные ноты одной высоты слога не берут.
  • ~ соединяет два слога под одной нотой (de~a-trás), но гравировщик печатает между ними обычный пробел, а не лигу.
  • По возможности пишите аккорды без ♭ и ♯: в большинстве текстовых шрифтов таких знаков нет, и страница берёт системный шрифт. Выбирайте тональности с аккордами без знаков (G, C, D7, Em), а в прозе пишите си-бемоль словом.

Источники и лицензии

Рецепт
Ignacio Ferro
Текст
Шрифты
Spectral (SIL OFL 1.1) · Spectral SC (SIL OFL 1.1) · Fraunces (SIL OFL 1.1)
SandboxPDF