This documentation covers a prerelease version of the software. Follow this link to view the documentation for the stable version (3.0) instead.

Tree Processor Extension Example

Purpose

Walk all paragraph blocks in the parsed document, count the total number of words, and set a reading-time document attribute (e.g., 2 min) that authors can reference anywhere in the document with {reading-time}.

sample-guide-doc.adoc

= Getting Started Guide

Estimated reading time: {reading-time}

== Installation

Download and install the package using your preferred package manager.
Run `npm install @asciidoctor/core` to add Asciidoctor.js to your project.

== Configuration

Open the configuration file and set your API key.
Make sure to keep your credentials private and never commit them to version control.
You can also configure the base URL and timeout values in this file.

ReadingTimeTreeProcessor

reading-time-tree-processor.js
export default function (registry) {
  registry.treeProcessor(function () {
    this.process(function (doc) {
      const words = doc.findBy({ context: 'paragraph' })
        .reduce((total, block) => total + block.getSource().split(/\s+/).length, 0)
      doc.setAttribute('reading-time', `${Math.ceil(words / 200)} min`)
      return doc
    })
  })
}

Usage

import { Extensions, convertFile } from '@asciidoctor/core'
import registerReadingTimeTreeProcessor from './reading-time-tree-processor.js'

const registry = Extensions.create()
registerReadingTimeTreeProcessor(registry)

const html = await convertFile('sample-guide-doc.adoc', { to_file: false, extension_registry: registry })
// <p>Estimated reading time: 1 min</p>