Software & Plugins/commonmark-ext-heading-shifter
PHP library · PHP

CommonMark Heading Shifter

A CommonMark extension that shifts heading levels by a configurable amount, so Markdown written for one context renders correctly in another.

License MIT Published on Packagist

What it does

CommonMark Heading Shifter is a small extension for League CommonMark, the go-to Markdown parser for PHP. It shifts every heading in a document up or down by a fixed number of levels, so the same Markdown source can sit correctly inside different page layouts.

It is useful whenever Markdown written to stand alone (where # is the top heading) has to be embedded under an existing heading, for example in a documentation system, a blog engine or a static site generator that already prints its own h1. Instead of rewriting the source or patching the renderer, you configure a single offset.

Install

composer require tuchsoft/commonmark-ext-heading-shifter

Requires PHP 8 and League CommonMark. The package is published on Packagist as tuchsoft/commonmark-ext-heading-shifter.

Usage

use League\CommonMark\CommonMarkConverter;
use TuchSoft\CommonMarkHeadingShifter\HeadingShifterExtension;

$converter = new CommonMarkConverter([
    'heading_shifter' => [
        'shift_by' => 1,
    ],
]);

$converter->getEnvironment()->addExtension(new HeadingShifterExtension());

echo $converter->convertToHtml("# Heading"); // <h2>Heading</h2>

Set shift_by to a positive number to push headings down, or a negative one to pull them up. The offset applies to every heading in the document, including the ones produced by table-of-contents and heading-permalink extensions.

Why we built it

This very website is written in Markdown and rendered with League CommonMark. When the same Markdown is reused in a context that already owns the top of the heading hierarchy, the levels have to move. Rather than special-case it in the builder, we extracted the logic into a tiny, reusable extension and released it under the MIT license, so anyone running CommonMark on PHP can do the same.