Skip to main content
Recipe number 186

Cookbook · Chapter 2 · Type & text

Citations and statistics kept off the line edges

A two-column clinical paper set twice: the first proof reports every citation or sign left at a line edge, the second prices those breaks in the line breaker.

p. 211 · 1 of 6

  • Trim 170 × 240 mm
  • 2 columns, 6 mm gutter
  • STIX Two Text 9.5/12.8
  • IBM Plex Sans
  • IBM Plex Sans Condensed
  • 6 pages
  • Level
  • Postext 1.79.0
  • Laid out in 153 ms
  • 180 lines of code

In short

In a narrow justified column a reference number such as [2, 3] can start a line on its own, and p < 0.05 can split after the sign. The paper is set twice: once showing where that happens, once with the lines broken so it mostly doesn't.

What you'll build

Three pages of a paediatric journal, 170 × 240 mm, set in two justified columns of 66 mm in STIX Two Text: an original study of lung ultrasound for pneumonia with a numbered Vancouver reference list. A column that narrow gives the line breaker few choices, and in three places the English text breaks badly. A citation, [2, 3], starts a line on its own, away from the word it supports, and twice the likelihood ratio LR− = 0.09 splits after the equals sign. The first proof is set with citationBreaks and operatorBreaks at 'warn'. It changes no break, marks each one with a pale amber band and lists them on a slip after the references. The second proof is set with 'avoid', and one of the three is left. The Spanish edition sets the same study with a decimal comma.

This recipe answers

  • How do I keep a citation number or a statistic such as p < 0.05 from breaking at the end of a line?
  • How do I set citation numbers as superscripts and make DOIs live links, as medical journals do?

The short answer

script.js · lines 27–42in full code
const bodyText = {
  fontFamily: SERIF, fontSize: pt(9.5), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
  referenceBold: false, textAlign: 'justify', firstLineIndent: mm(3.5),
  indentAfterHeading: false, hyphenation: { enabled: true },
  optimalLineBreaking: true, // the rules price breaks in the Knuth–Plass breaker
  avoidWidows: true, avoidOrphans: true, avoidRunts: true,
  // A line that opens on a citation, "[8, 9]" (citationBreak), or ends or opens on a sign
  // set between spaces, "p <" / "0.05" (operatorBreak). 'warn' reports each one and changes
  // nothing; 'avoid' adds the penalty to the demerits of those breaks and reports the ones
  // it keeps. The first proof sets 'warn' (see proofs).
  citationBreaks: 'avoid', operatorBreaks: 'avoid',
  // 10000 by default, what a line spaced to the limit costs. A 66 mm column offers few other
  // breaks; at 30000 the breaker takes looser lines, never past maxWordSpacing.
  citationBreakPenalty: 30000, operatorBreakPenalty: 30000,
};

No line opens on a citation, no line ends or opens on a lone sign

Ingredients

Type
STIX Two Text, IBM Plex Sans, IBM Plex Sans Condensed (SIL OFL 1.1)
Assets
None: every picture is drawn in code

Method

#1 · A price on two kinds of break

The code is the short answer above. A citation break is a line that starts with a numbered citation, or with the second half of one, such as 5] after [4,. An operator break is a line that ends or starts on a sign set between spaces: =, <, ±, ×, the minus. 'warn' reports both and leaves the lines as they are. 'avoid' adds a penalty to the demerits of those breaks, and the Knuth–Plass breaker looks for another way to set the paragraph. It needs optimalLineBreaking, since the greedy breaker has no demerits to add to.

The default penalty, 10000, is what a line stretched to the word-spacing limit costs, so the breaker never opens a line past that limit to keep a citation with its word. In this column 10000 left two breaks in each edition. At 30000 the breaker takes looser lines, still within maxWordSpacing, and one break is left in each. A higher value changed nothing more: the last break has no alternative within the limit.

#2 · Mark the breaks in the text

script.js · lines 254–279in full code
// The word before the citation and the citation, or the sign and the number on its other
// side, wrapped in :mark[…]: a band under ordinary text, so the breaks stay where they were.
const wordEnd = (s, i) => i + s.slice(i).search(/[\s;)]|[,.](?!\d)|$/); // 0.09, not 0
function sides(source, w, a, b) { // a warning names line a, before the break, by its source
  if (w.kind === 'citationBreak') { // "colleagues [@simel1991]"
    const cite = source.lastIndexOf('[@', b.sourceStart + 2);
    return [source.lastIndexOf(' ', cite - 2) + 1, source.indexOf(']', cite) + 1];
  }
  if (w.edge === 'end') { // "LR− = 0.09": the sign ends line a, the number opens line b
    const from = source.lastIndexOf(` ${w.text} `, a.sourceEnd) + 1;
    return [from, wordEnd(source, from + w.text.length + 1)];
  }
  const sign = source.indexOf(` ${w.text} `, b.sourceStart - 1); // the sign opens line b
  return [source.lastIndexOf(' ', sign - 1) + 1, sign + 1 + w.text.length];
}
function markBreaks(source, doc, found) {
  const pairs = doc.blocks.flatMap((b) => b.lines.map((line, i) => [line, b.lines[i + 1]]));
  const spans = new Map();
  for (const w of found) {
    const [a, b] = pairs.find(([line]) => line.sourceStart === w.sourceStart) ?? [];
    const [from, to] = b ? sides(source, w, a, b) : [];
    if (from > a?.sourceStart && to > from && to <= b.sourceEnd) spans.set(from, to);
  }
  return [...spans].sort(([x], [y]) => y - x).reduce((md, [from, to]) => `${md.slice(0, from)}`
    + `:mark[${md.slice(from, to)}]{style="edge"}${md.slice(to)}`, source);
}

Each warning carries its kind, the citation or the sign, the text of the two lines, the source position of the first one and the page. The script finds those two lines in the built document and wraps the break in :mark[…]: the word before a citation and the citation, or the sign and the number on its other side. A mark paints a band under the text and leaves the breaks where they were. The band does not reach the number the citation style generates, so on the page only the word before it is marked.

First proof, page 211: LR− = 0.09 split in the abstract, and first at a line end with [2, 3] opening the next line.

#3 · Two proofs and a query slip

script.js · lines 283–303in full code
const KIND = { citationBreak: t({ en: 'citation', es: 'cita' }),
  operatorBreak: t({ en: 'sign', es: 'signo' }) };
const edge = (s, end) => (end ? s.trim().split(/\s+/).slice(-2) : s.trim().split(/\s+/)
  .slice(0, 2)).join('\u00a0').replace(/[.,;]$/, ''); // no-break spaces: no breaks of its own
const query = (doc, w) => `${t({ en: 'p.', es: 'pág.' })}\u00a0${doc.pages[w.pageIndex]
  .pageLabel}, ${KIND[w.kind]}: …${edge(w.lines[0], true)}\u00a0/ ${edge(w.lines[1])}…`;
const slip = (mode, doc, found) => ['', `:::callout{type="slip" title="${mode === 'warn'
  ? t({ en: 'First proof: queries', es: 'Primeras pruebas: consultas' })
  : t({ en: 'Second proof: queries', es: 'Segundas pruebas: consultas' })}"}`,
`citationBreaks / operatorBreaks: '${mode}' · ${found.length} ${found.length === 1
  ? t({ en: 'break', es: 'corte' }) : t({ en: 'breaks', es: 'cortes' })}.`,
...found.flatMap((w) => ['', query(doc, w)]), ':::', ''].join('\n');
const build = (md, mode) => buildDocumentWithFonts({ markdown: md }, { ...config,
  bodyText: { ...bodyText, citationBreaks: mode, operatorBreaks: mode } }, kitFonts(FONTS));
async function proof(mode) {
  const plain = await build(markdown, mode); // pass 1: where the breaks are
  const found = (plain.contentWarnings ?? []).filter((w) => /^(citation|operator)Break$/
    .test(w.kind));
  return build(markBreaks(markdown, plain, found) + slip(mode, plain, found), mode); // pass 2
}
const docs = { warn: await proof('warn'), avoid: await proof('avoid') };

Each proof is built twice. The first build finds the breaks; the second sets the article with the marks and a slip after the references, so the slip falls on the last page. A typesetter returns proofs with queries in the same way. The slip's lines join their words with no-break spaces, so they add no breaks of their own. capture.doc publishes the two marked builds, [1, 3].

Second proof, page 213: the slip lists one break left in the article.

The break left in English is first over [2, 3] on page 211. In Spanish the first proof finds four, among them CP+ over = 19,19 and [4, over 5] where the citation itself splits, and the second proof keeps one, anteriores [4, over 5].

#4 · Numbered citations in brackets

script.js · lines 46–50in full code
registerCitationEngine(createCiteprocEngine({ styles: STYLES, locales: LOCALES }));
const citations = { style: 'elsevier-vancouver', locale: t({ en: 'en-GB', es: 'es-ES' }),
  marker: 'brackets', collapseRanges: true, // [8, 9] and [4–6], set after a word space
  bibliography: { fontSize: em(0.8), lineHeight: pt(9.6), entrySpacing: pt(1),
    labelWidth: mm(6), labelAlign: 'right', doi: 'hide' } };

The citation processor sets each [@key] as a bracketed number after a word space and collapses runs such as [4–6]. The space before the bracket and the space after a comma inside it are both places a line can break, which is why a narrow column with many citations needs the rule.

#5 · The masthead and the article block

script.js · lines 54–78in full code
const text = (id, content, family, size, extra) => ({ kind: 'text', id, content, align: 'left',
  fontFamily: family, fontSize: pt(size), color: col('ink'), overflow: 'wrap', ...extra });
const at = (to, edge, x, y, width) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
  ...(width && { size: { width: mm(width), height: 'auto' } }) });
const caps = { fontFamily: COND, fontWeight: 600, letterSpacing: pt(1.2),
  textTransform: 'uppercase' };
const JOURNAL = t({ en: 'Ribera Paediatric Journal', es: 'Revista Pediátrica de la Ribera' });
const white = { ...caps, color: col('paper') };
const titleBlock = { enabled: true, minHeight: mm(58), slot: { elements: [
  { kind: 'box', id: 'band', style: { backgroundColor: col('accent') }, placement: {
    anchor: { to: 'page', edge: 'top-left' }, size: { width: 'fill', height: mm(13) } } },
  text('journal', JOURNAL, COND, 9, { ...white, placement: at('page', 'top-left', INNER, 5) }),
  text('issue', '{attr.issue}', COND, 9, { ...white, align: 'right',
    placement: at('page', 'top-right', -OUTER, 5, 60) }),
  text('kind', '{attr.kind}', COND, 8.5, { ...caps, color: col('accent'),
    placement: at('container', 'top-left', 0, 0, MEASURE) }),
  text('title', '{titleText}', SANS, 16, { fontWeight: 600, lineHeight: 1.18,
    placement: at('#kind', 'below', 0, 2.5, MEASURE - 6) }),
  text('authors', '{attr.authors}', SERIF, 10, { inlineMarks: true, // ^1^ → ¹
    placement: at('#title', 'below', 0, 3.5, MEASURE) }),
  text('affiliations', '{attr.affiliations}', SANS, 7.2, { inlineMarks: true, lineHeight: 1.35,
    color: col('muted'), placement: at('#authors', 'below', 0, 1.6, MEASURE) }),
  text('note', '{attr.note}', SANS, 7.2, { color: col('muted'),
    placement: at('#affiliations', 'below', 0, 2.4, MEASURE) }),
] } };

The heading style draws the journal band, the article type, the title, the authors with their affiliation numbers and a note, all from attributes on the H1. The two editions share the style, and the text stays in the Markdown.

The whole recipe

Sandbox
// ═══ Postext Cookbook · Nº 186 · Citations and statistics off the line edges ═══════════
// https://postext.dev/en/cookbook/clinical-paper-line-edges
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: STIX Two Text, IBM Plex Sans and Sans Condensed (SIL OFL 1.1) · Needs postext ≥ 1.79.0
import {
  buildDocumentWithFonts, renderPageToCanvas, registerCitationEngine,
} from 'https://esm.sh/postext';
import { createCiteprocEngine, STYLES, LOCALES } from 'https://esm.sh/postext-citeproc';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'clinical-paper-line-edges';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: an indigo journal, a pale amber band for the proof marks
const palette = { ink: '#1b1e26', accent: '#2c4a7c', tint: '#e9eef6', mark: '#f7dfa9',
  muted: '#596173', paper: '#ffffff' };
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = Object.entries({ ...palette, 'main-color': palette.accent })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
// #endregion
const [SERIF, SANS, COND] = ['STIX Two Text', 'IBM Plex Sans', 'IBM Plex Sans Condensed'];
const [TRIM_W, TRIM_H, TOP, BOTTOM, INNER, OUTER, GUTTER] = [170, 240, 20, 22, 17, 15, 6];
const MEASURE = TRIM_W - INNER - OUTER; // 138 mm: two columns of 66 mm, about 45 characters
const LEAD = 12.8; // pt, for 9.5 pt type

// #region answer: no line opens on a citation, no line ends or opens on a lone sign
const bodyText = {
  fontFamily: SERIF, fontSize: pt(9.5), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
  referenceBold: false, textAlign: 'justify', firstLineIndent: mm(3.5),
  indentAfterHeading: false, hyphenation: { enabled: true },
  optimalLineBreaking: true, // the rules price breaks in the Knuth–Plass breaker
  avoidWidows: true, avoidOrphans: true, avoidRunts: true,
  // A line that opens on a citation, "[8, 9]" (citationBreak), or ends or opens on a sign
  // set between spaces, "p <" / "0.05" (operatorBreak). 'warn' reports each one and changes
  // nothing; 'avoid' adds the penalty to the demerits of those breaks and reports the ones
  // it keeps. The first proof sets 'warn' (see proofs).
  citationBreaks: 'avoid', operatorBreaks: 'avoid',
  // 10000 by default, what a line spaced to the limit costs. A 66 mm column offers few other
  // breaks; at 30000 the breaker takes looser lines, never past maxWordSpacing.
  citationBreakPenalty: 30000, operatorBreakPenalty: 30000,
};
// #endregion

// #region citations: numbered references in brackets, the list in the Vancouver order
registerCitationEngine(createCiteprocEngine({ styles: STYLES, locales: LOCALES }));
const citations = { style: 'elsevier-vancouver', locale: t({ en: 'en-GB', es: 'es-ES' }),
  marker: 'brackets', collapseRanges: true, // [8, 9] and [4–6], set after a word space

The composed script.js runs as it is: paste it into any page’s module script, or open the recipe on CodePen. Recipe folder on GitHub ↗ (opens in a new tab)

Variations

#Report the breaks and change nothing

A journal that checks its proofs by hand can keep the rule at 'warn': the Sandbox lists each break in Review, and the lines stay as the breaker set them.

-  citationBreaks: 'avoid', operatorBreaks: 'avoid',
+  citationBreaks: 'warn', operatorBreaks: 'warn',

#Keep the default penalty

At 10000 the spacing stays a little tighter and two breaks are left in each edition instead of one.

-  citationBreakPenalty: 30000, operatorBreakPenalty: 30000,

Pitfalls

Layout warning · citationBreak

Citation at line start

Why. A line of a paragraph starts with a numbered citation set after a word, or with a piece of one: “authors” at the end of one line and “[12]” at the head of the next, or “[14,” over “16]”. A number in brackets or parentheses after a number is no citation (“2016 (3)”), nor a word in brackets. Right-to-left and Chinese, Japanese or Korean text is left alone. With bodyText.citationBreaks on 'warn' every such break is reported; on 'avoid', the ones the line breaker kept because no setting within the word spacing avoided them for less than bodyText.citationBreakPenalty. The engine lists each in doc.contentWarnings with the citation, the two lines and their page.

Fix. Set bodyText.citationBreaks to 'avoid': the line breaker prices a break before or inside a citation and sets the paragraph otherwise where the word spacing allows; the space still stretches with the others. A break that stays costs more to avoid than bodyText.citationBreakPenalty, often because the citation is wide for the measure: raise the penalty to trade looser lines for it, or write a no-break space (U+00A0) between the word and the citation to bind that pair whatever the rule. In a port of an existing book keep 'warn': the port reproduces the original's breaks. Docs →

Layout warning · operatorBreak

Sign at line edge

Why. A line of a paragraph ends or starts on a lone sign set between spaces, one of = < > ≤ ≥ ± × ≈ ≠ ÷ − + · →: “LR+ =” at the end of a line with “18.29” on the next, or “± 0.03” at the head of a line. A hyphen between words is no sign. Right-to-left and Chinese, Japanese or Korean text is left alone. With bodyText.operatorBreaks on 'warn' every such break is reported, one per break (a line that starts and ends on a sign gives two); on 'avoid', the ones the line breaker kept because no setting within the word spacing avoided them for less than bodyText.operatorBreakPenalty. The engine lists each in doc.contentWarnings with the sign, the edge (end or start), the two lines and their page.

Fix. Set bodyText.operatorBreaks to 'avoid': the line breaker prices a break at the spaces on either side of the sign and sets the paragraph otherwise where the word spacing allows. A break that stays costs more to avoid than bodyText.operatorBreakPenalty, often in a narrow column where the sign and its two terms are wide: raise the penalty to trade looser lines for it, or write no-break spaces (U+00A0, or U+202F for a thin one) around the sign to bind it whatever the rule. In a port of an existing book keep 'warn': the port reproduces the original's breaks. Docs →

  • The breaks are found in the lines as broken. A change of trim, size or text moves them, so read the warnings of each build rather than copying positions from an earlier one.
  • To keep one citation with its word whatever the column, type a no-break space before it in the Markdown. The rule does the rest of the paper.

Credits

Text
Original prose, CC BY 4.0
Fonts
STIX Two Text (SIL OFL 1.1) · IBM Plex Sans (SIL OFL 1.1) · IBM Plex Sans Condensed (SIL OFL 1.1)
Sandbox