or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

cli.mdfile-utilities.mdindex.mdprogrammatic-api.md
tile.json

programmatic-api.mddocs/

Programmatic API

DocToc's programmatic API enables integration of TOC generation into Node.js applications, build processes, and custom workflows.

Capabilities

Transform Function

Core transformation function for generating table of contents from markdown content.

/**
 * Generate table of contents for markdown content
 * @param {string} content - Markdown content to process
 * @param {string} [mode='github.com'] - Platform mode for anchor compatibility
 * @param {number} [maxHeaderLevel] - Maximum header level to include (1-6)
 * @param {string} [title] - Custom TOC title
 * @param {boolean} [notitle=false] - Whether to omit the TOC title
 * @param {string} [entryPrefix='-'] - Prefix character for TOC entries
 * @param {boolean} [processAll=false] - Include headers before TOC location
 * @param {boolean} [updateOnly=false] - Only process if TOC markers exist
 * @returns {TransformResult} Result object with transformation data
 */
function transform(
  content,
  mode,
  maxHeaderLevel, 
  title,
  notitle,
  entryPrefix,
  processAll,
  updateOnly
);

Transform Result

Result object returned by the transform function.

interface TransformResult {
  /** Whether the content was modified */
  transformed: boolean;
  /** Updated markdown content (if transformed) */
  data?: string;
  /** Generated TOC content without HTML comment wrapper */
  toc?: string;
  /** Generated TOC content with HTML comment wrapper */
  wrappedToc?: string;
}

Platform Modes

Supported platform modes for anchor compatibility.

// Available mode strings
'github.com'     // GitHub-compatible anchors (default)
'gitlab.com'     // GitLab-compatible anchors  
'bitbucket.org'  // Bitbucket-compatible anchors
'nodejs.org'     // Node.js documentation style
'ghost.org'      // Ghost publishing platform

Usage Examples:

const { transform } = require('doctoc');

// Basic usage with GitHub mode
const result = transform(content, 'github.com');

// GitLab mode with custom options
const result = transform(
  content,
  'gitlab.com',
  3,              // maxHeaderLevel
  'Contents',     // title  
  false,          // notitle
  '*',            // entryPrefix
  false,          // processAll
  false           // updateOnly
);

Header Level Control

Control which header levels are included in the generated TOC.

/**
 * @param {number} maxHeaderLevel - Maximum header level (1-6)
 */
transform(content, 'github.com', 3); // Only H1, H2, H3 headers

Header Level Examples:

// Include all headers (H1-H6)
transform(content, 'github.com', 6);

// Only top-level headers (H1-H2)  
transform(content, 'github.com', 2);

// Default behavior (HTML headers limited to H4, markdown headers unlimited)
transform(content, 'github.com');

Title Customization

Control TOC title generation and display.

// Custom title
transform(content, 'github.com', null, 'Table of Contents');

// No title
transform(content, 'github.com', null, null, true);

// Default title (inferred from existing or generated)
transform(content, 'github.com');

Title Behavior:

  • If notitle is true: No title is added
  • If title is provided: Uses the custom title
  • If TOC already exists: Preserves existing title
  • Default: Generates standard title with DocToc attribution

Entry Prefix Customization

Customize the prefix character for TOC entries.

// Custom prefix
transform(content, 'github.com', null, null, false, '*');

// Default prefix (hyphen)
transform(content, 'github.com', null, null, false, '-');

Example Output:

// With default prefix '-'
// - [Header 1](#header-1)
//   - [Header 1.1](#header-11)

// With custom prefix '*'  
// * [Header 1](#header-1)
//   * [Header 1.1](#header-11)

Processing Control Options

Control how TOC generation and placement works.

// Include headers before TOC location
transform(content, 'github.com', null, null, false, '-', true);

// Only update existing TOCs
transform(content, 'github.com', null, null, false, '-', false, true);

Option Behavior:

  • processAll: Includes headers that appear before the TOC insertion point
  • updateOnly: Only processes content that already contains TOC HTML comment markers

Complete Usage Examples

Basic File Processing:

const { transform } = require('doctoc');
const fs = require('fs');

// Read and process file
const content = fs.readFileSync('README.md', 'utf8');
const result = transform(content, 'github.com');

if (result.transformed) {
  fs.writeFileSync('README.md', result.data, 'utf8');
  console.log('TOC updated successfully');
} else {
  console.log('No changes needed - TOC is up to date');
}

Custom Configuration:

const { transform } = require('doctoc');

const result = transform(
  markdownContent,
  'gitlab.com',           // GitLab mode
  4,                      // Max H4 headers
  'Document Contents',    // Custom title
  false,                  // Include title
  '-',                    // Hyphen prefix
  true,                   // Process all headers
  false                   // Create new TOC if needed
);

if (result.transformed) {
  console.log('Generated TOC:');
  console.log(result.toc);
}

Build Process Integration:

const { transform } = require('doctoc');
const glob = require('glob');
const fs = require('fs');

// Process all markdown files in docs directory
const files = glob.sync('docs/**/*.md');

files.forEach(file => {
  const content = fs.readFileSync(file, 'utf8');
  const result = transform(
    content,
    'github.com',
    3,                    // H1-H3 only
    null,                 // Default title
    false,                // Include title
    '-',                  // Default prefix
    false,                // Standard processing
    true                  // Update only existing TOCs
  );
  
  if (result.transformed) {
    fs.writeFileSync(file, result.data, 'utf8');
    console.log(`Updated TOC in ${file}`);
  } else {
    console.log(`${file} - no changes needed`);
  }
});

Error Handling

The transform function handles various error conditions gracefully.

Skip Processing:

  • Content containing <!-- DOCTOC SKIP --> returns { transformed: false }

No Headers Found:

  • Content with no headers returns { transformed: false }

Update Only Mode:

  • Content without existing TOC markers in update-only mode returns { transformed: false }

Content Unchanged:

  • If generated TOC matches existing TOC returns { transformed: false }

Transform Module Constants

Additional exports from the transform module.

const { start, end } = require('doctoc/lib/transform');

// HTML comment markers
const start = '<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON\'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->';

const end = '<!-- END doctoc generated TOC please keep comment here to allow auto update -->';

These constants can be used to manually add TOC markers to markdown content.