Skip to main content
Recipe number 212

Cookbook · Chapter 13 · CMS integration

Select on the page, read the Markdown range and text

postext-viewer reports a selection on the laid-out pages as a range of the Markdown, the Markdown it covers and its pieces line by line.

On this page
Output
Canvas
Level
Basic
Postext
Tested with Postext 1.103.1
Needs ≥ 1.103.0
Licence
Updated 4 Dec 2026
Code MIT · Text CC BY 4.0
A quote selected on page 1: the panel shows its range in the Markdown, the Markdown it covers with the emphasis marks, and the same words in the source.
A quote selected on page 1: the panel shows its range in the Markdown, the Markdown it covers with the emphasis marks, and the same words in the source.
  • Trim 140 × 210 mm
  • 1 column
  • Newsreader 10.5/15
  • Archivo
  • 2 pages
  • Level
  • Postext 1.103.1
  • Laid out in 53 ms
  • 104 lines of code

In short

An article on lighthouse lenses shown in a page viewer, with a panel beside it. When someone selects words on the page, the panel shows where those words sit in the source text and what the source says there, formatting marks included.

What you'll build

A two-page article on lighthouse lenses, shown in a page viewer with a panel on its right, like the one a review tool keeps beside a passage under discussion. One sentence on the first page is selected, and the panel reads it back three ways: the range { start, end } in the Markdown file, the Markdown inside it, where the italic French name keeps its asterisks, and the whole paragraph with the selection marked. Drag across other words and the panel follows while you drag.

This recipe answers

  • How do I get the Markdown range and the text of what an editor selects on the page?

The short answer

script.js · lines 97–118in full code
const view = createViewer($('viewer'), {
  document: doc,
  markdown, // with it, each selection event carries the Markdown it covers
  zoom: 'fit-page', labels: L.viewer,
});
view.on('selectionchange', ({ range, text }) => {
  $('panel').classList.toggle('empty', !range);
  if (!range) return void ($('range').textContent = L.none);
  $('range').textContent = `{ start: ${range.start}, end: ${range.end} }`;
  $('text').textContent = text; // the Markdown, emphasis marks included
  // The range is a plain value: the core API places it too, one piece per line, in page px.
  const rects = rangeRects(doc, range);
  const pages = [...new Set(rects.map((r) => r.pageIndex + 1))].join(', ');
  $('lines').textContent = L.lines(rects.length, pages);
  // The paragraph around it: offsets count in the Markdown file, front matter included.
  const from = markdown.lastIndexOf('\n\n', range.start) + 2;
  let to = markdown.indexOf('\n\n', range.end);
  if (to < 0) to = markdown.length; // the last paragraph
  const mark = Object.assign(document.createElement('mark'), { textContent: text });
  const [before, after] = [markdown.slice(from, range.start), markdown.slice(range.end, to)];
  $('source').replaceChildren(before, mark, after);
});

The selection as a range of the Markdown, its source and its lines

Ingredients

Type
Newsreader, Archivo (SIL OFL 1.1)
Assets
None: every picture is drawn in code

Method

#1 · Lay out a page to select on

script.js · lines 29–50in full code
const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  layout: { layoutType: 'single' },
  page: { sizePreset: 'custom', width: mm(140), height: mm(210), dpi: 150,
    margins: { top: mm(20), bottom: mm(24), left: mm(22), right: mm(22) } },
  bodyText: { fontFamily: 'Newsreader', fontSize: pt(10.5), lineHeight: pt(15),
    color: col('ink'), boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'justify', firstLineIndent: mm(4), indentAfterHeading: false,
    hyphenation: { enabled: true }, optimalLineBreaking: true,
    avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: 'Archivo', color: col('accent'), fontWeight: 600, levels: [
    { level: 1, fontSize: pt(22), lineHeight: pt(26), marginTop: pt(6), marginBottom: pt(15) },
    { level: 2, fontSize: pt(10), lineHeight: pt(15), marginTop: pt(15), marginBottom: pt(0) },
  ] },
  header: { elements: [] },
  footer: { elements: [
    { kind: 'text', id: 'folio', content: '{pageNumber}', fontFamily: 'Archivo', fontSize: pt(8),
      fontWeight: 600, color: col('accent'), align: 'center',
      placement: { anchor: { to: 'page', edge: 'bottom-center' }, offset: { y: mm(-12) } } },
  ] },
};

A plain magazine page: one justified column of Newsreader, Archivo headings in harbour blue and a folio at the foot. Selection works the same on any layout, columns, right-to-left and vertical pages included, because the viewer asks the layout where each line was painted.

#2 · Read the selection as Markdown

The code is the short answer above. Pass markdown to createViewer and each selectionchange carries the range and the Markdown it covers. The range is a plain { start, end }, so the core rangeRects places it on the pages without the viewer, one piece per line it crosses. The offsets count in the Markdown file, front matter included, so the paragraph around a selection is a slice of the same string, and a range saved today points at the same words tomorrow if the text has not changed.

#3 · Restore a saved selection

script.js · lines 122–125in full code
const quote = t({ en: 'The first *lentille à échelons* was lit in July 1823',
  es: 'La primera *lentille à échelons* se encendió en julio de 1823' });
const start = markdown.indexOf(quote);
view.setSelection({ start, end: start + quote.length });

setSelection takes a range from code and fires the same events as a drag, so the panel fills on its own. A tool reopening a comment's passage does this; Anchors and edits keeps such a range valid after the text is edited.

The whole recipe

// ═══ Postext Cookbook · Nº 212 · Select on the page, read the Markdown range and text ═══
// https://postext.dev/en/cookbook/selection-as-markdown-range
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Newsreader, Archivo (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// An article on lighthouse lenses in postext-viewer, with a panel beside it that a review
// tool would fill from the selection: the range in the Markdown, the Markdown it covers and
// the paragraph around it. The pen selects one sentence itself; drag over the page to change it.
import { buildDocumentWithFonts, renderPageToCanvas, rangeRects } from 'https://esm.sh/postext';
import { createViewer } from 'https://esm.sh/postext-viewer';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'selection-as-markdown-range';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
  ink: '#1b1f24', // text: a cool near-black
  accent: '#1d5c73', // harbour blue: headings and folio
};
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' } })),
  { id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
// #endregion

// #region page: a magazine page, one column, a folio at the foot
const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  layout: { layoutType: 'single' },
  page: { sizePreset: 'custom', width: mm(140), height: mm(210), dpi: 150,
    margins: { top: mm(20), bottom: mm(24), left: mm(22), right: mm(22) } },
  bodyText: { fontFamily: 'Newsreader', fontSize: pt(10.5), lineHeight: pt(15),
    color: col('ink'), boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'justify', firstLineIndent: mm(4), indentAfterHeading: false,
    hyphenation: { enabled: true }, optimalLineBreaking: true,
    avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: 'Archivo', color: col('accent'), fontWeight: 600, levels: [
    { level: 1, fontSize: pt(22), lineHeight: pt(26), marginTop: pt(6), marginBottom: pt(15) },
    { level: 2, fontSize: pt(10), lineHeight: pt(15), marginTop: pt(15), marginBottom: pt(0) },
  ] },
  header: { elements: [] },
  footer: { elements: [
    { kind: 'text', id: 'folio', content: '{pageNumber}', fontFamily: 'Archivo', fontSize: pt(8),
      fontWeight: 600, color: col('accent'), align: 'center',
      placement: { anchor: { to: 'page', edge: 'bottom-center' }, offset: { y: mm(-12) } } },

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

#Act only when the selection is made

selectionchange fires on every step of a drag; select fires once, when the pointer is released or a word is double clicked.

-view.on('selectionchange', ({ range, text }) => {
+view.on('select', ({ range, text }) => {

#Read it at the width of the column

At the column's width the selection is easier to drag with precision.

-  zoom: 'fit-page', labels: L.viewer,
+  zoom: 'fit-width', labels: L.viewer,

Credits

Text
Original prose, CC BY 4.0
Fonts
Newsreader (SIL OFL 1.1) · Archivo (SIL OFL 1.1)