Open skeets23 opened 5 years ago
Not sure if it's what you are looking for but I've made https://github.com/jenstornell/php-toc
It does not extend Parsedown but you can use it afterwards by manipulate the html.
$toc = new TOC();
$text = $toc->anchorHeadings($html);
echo $toc->list($html);
echo $text;
I've not had the time to write any docs or add screenshots to the repo, but the end result will look like this:
This is actually a problem with Parsedown. I noticed this too and was pleased to find I'm not the only one. Basically, if you link to any existing Header (#), GFM on GitHub makes it an anchor'd header so you can have a link directly to a subitem within the markdown.
For example, if you visit Cacti's documentation README.md (https://github.com/cacti/documentation), there are various levels of headers. If you hover on the left of the topic, you will see:
If you copy the link presented by the overlapping squares, you will see that it contains an anchor'd link: https://github.com/cacti/documentation#cacti-installation
This means, people can be sent straight to that section which can be important when providing end users with exactly where they need to go. Markdown will render the links in the page in the same way so that they contain the in-page reference, but that reference doesn't work as it isn't generated.
I'm trying to see how you modify the block code to also append a reference text (with spaces converted to hyphen's as per GitHub's model):
$Block = array(
'element' => array(
'name' => 'h' . $level,
'handler' => array(
'function' => 'lineElements',
'argument' => $text,
'destination' => 'elements',
),
),
);
But at the moment, I'm not sure if it's possible since the 'element' needs to be wrapped in another element effectively (a name='cacti-installion').
So I had a play, as I like to tinker when I have issues like this and came up with the following:
diff --git a/Parsedown.php b/Parsedown.php
index ae0cbde..6e2a8e1 100644
--- a/Parsedown.php
+++ b/Parsedown.php
@@ -553,15 +553,19 @@ class Parsedown
}
$text = trim($text, ' ');
+ $link = strtolower(str_replace(' ','-',$text));
$Block = array(
'element' => array(
'name' => 'h' . $level,
+ 'attributes' => array(
+ 'id' => $link,
+ ),
'handler' => array(
'function' => 'lineElements',
'argument' => $text,
'destination' => 'elements',
- )
+ ),
),
);
@@ -1992,3 +1996,4 @@ class Parsedown
'wbr', 'time',
);
}
Apparently, it's as simple as that.
For example, try the readme file here:
https://github.com/CodepadME/laravel-tricks
In GitHub, it works as expected, because:
## Title
is translated to:
While this library translates it to:
<h2>Title</h2>
So, basically it's missing the anchor.