Search by

trail / markdown

dodgycoffee

Markdown w/ custom syntax support for trail

0.5.0 2026-11-16 06:58 UTC

This package is auto-updated.

Last update: 2026-11-16 23:29:15 UTC


README

Markdown parser for trail w/ custom syntax support

install

composer require trail/markdown

use

use Trail\Markdown\Markdown;

$markdown = new Markdown();

$markdown->html('**hi** there');
$markdown->text('**hi** there');   // plain text, for emails

Everything runs through a purifier so random JS stuff and the like gets handled

syntax

Supports standard syntax out of the box

options

new Markdown(
    rawHtml: true,    // keep html (purified)
    breaks: true,     // newlines are <br>
    figures: true,    // images wrap in <figure>. caption is the title
    permit: Permit::richText(['links', 'lists'], headings: [2, 3]),
);

You can snap excluded ones to the closest enabled if you want. I doubt anyone will actually use this aside from me that one time

Permit::richText(headings: [4, 5, 6])->rename(['h1' => 'h4', 'h2' => 'h5', 'h3' => 'h6']);

custom syntax

$markdown = new Markdown()
    ->mark('==', 'mark')         // ==highlight==
    ->mark('~', 'sub')           // H~2~O
    ->inline(new Mentions())     // @alex
    ->block(new Callouts())      // ::: warning
    ->links(function (Link $link): void {
        $link->attributes['rel'] = 'nofollow';
    });
final readonly class Mentions implements Inline
{
    public function starts(): string
    {
        return '@';
    }

    public function parse(string $text, int $at, Parse $parse): ?Piece
    {
        if (1 !== preg_match('/\G@([a-z0-9_]+)/i', $text, $match, 0, $at)) {
            return null;
        }

        return new Piece('<a href="/u/' . $match[1] . '" class="mention">@' . $match[1] . '</a>', $at + strlen($match[0]));
    }

    public function tags(): array
    {
        return ['a' => ['class']];
    }
}
final readonly class Callouts implements Block
{
    public function starts(string $line): bool
    {
        return str_starts_with($line, '::: ');
    }

    public function parse(array $lines, int $at, Parse $parse): ?Piece
    {
        $inner = [];

        for ($at++; $at < count($lines) && ':::' !== trim($lines[$at]); $at++) {
            $inner[] = $lines[$at];
        }

        return new Piece('<div class="callout">' . $parse->nest($inner) . '</div>', $at + 1);
    }

    public function tags(): array
    {
        return ['div' => ['class']];
    }
}

twig

You can register your markdown in box. Then add extensions

$box->factory(Markdown::class, static function (): Markdown {
    return new Markdown(breaks: true)->inline(new Mentions());
});

Twig::extension(MarkdownTwig::class);
{{ comment.body|markdown }}
{{ comment.body|markdownText }}