KEINOS/parsedown-extension_table-of-contents

Multiple or custom replace tag

Closed this issue · 3 comments

vnq commented

Could we support either multiple replace tags like [toc]so we can allow [toc], [[_TOC_]], {:toc} etc.

For reference see: https://gitlab.com/gitlab-org/gitlab/-/issues/21901#note_280349199

Or a way to override the const TAG_TOC so I can change it to my liking, in my case [[_TOC_]].

Do you mean a user-defined ToC tag? Cool! Let's do it.

By chance, I was refactoring some in organize-test-suite branch and the below part might help us implement this. A getter method to get the ToC tag.

/**
* ------------------------------------------------------------------------
* Constants.
* ------------------------------------------------------------------------
*/
const version = '1.1.1'; // Version is available since v1.1.0
const VERSION_PARSEDOWN_REQUIRED = '1.7';
const TAG_TOC_DEFAULT = '[toc]';
const ID_ATTRIBUTE_DEFAULT = 'toc';

/**
* Gets the markdown tag for ToC.
*
* @return string
*/
protected function getTagToC()
{
if (isset($this->tag_toc) && ! empty($this->tag_toc)) {
return $this->tag_toc;
}
return self::TAG_TOC_DEFAULT;
}

/**
* Replaces the "[toc]" tag (by default) to the parsed ToC list.
*
* @param string $html Parsed HTML string
* @return string Parsed HTML string with parsed ToC.
*/
protected function replaceTagToC($html)
{
$toc = $this->contentsList();
$tag_toc = $this->getTagToC();
$id_toc = $this->getIdAttributeToC();
$needle = '<p>' . $tag_toc . '</p>';
$replace = "<div id=\"${id_toc}\">${toc}</div>";
return str_replace($needle, $replace, $html);
}

So, implementing the setter method might satisfy our needs. Doesn't it?

As soon as I merge the organize-test-suite branch, I will draft a PR for this request!

@vnq

I believe there must be a smarter way to implement but I released v1.1.2 which implements your request. Thank you for the cool request!

Please update the plug-in and use the setTagToc('[[_TOC_]]') method to set the ToC markdown tag you like. Hope this suits your needs! 🤞

<?php
require_once __DIR__ . '/vendor/autoload.php';

$text_markdown = file_get_contents('SAMPLE.md');

$Parsedown = new \ParsedownToC();
$Parsedown->setTagToc('[[_TOC_]]');

$html = $Parsedown->text($text_markdown);
echo $html . PHP_EOL;

These are the tests for the custom ToC tag

vnq commented

@KEINOS great job thanks for this!