Explanation
Closed this issue · 3 comments
Hi! Thanks for your plugin, it helped me for mkdocstrings.
I'm considering dropping the object references feature and recommend using your plugin. I tried it but it does not work with mine (yet). I guess it's simply a matter of selecting tags or else.
Or maybe I missed how it should be used? What is the reference format? [title](ref:section)
?
Also, could you explain to me what the code is doing? I understand most of it, but still couldn't wrap my head around the regexes you use. I think if you explain the high-level logic of it, it will help a lot 🙂
Thanks!
The format is just [section]
, similar to this Pandoc feature: https://pandoc.org/MANUAL.html#extension-implicit_header_references. There is no way to specify a link title, but it would be good to support this.
How it works:
on_nav
saves the page objects and markdown text for later. In on_page_content
we find all text of the form [section]
in the html page, and replace it with an html link if it corresponds to a heading or page. To do this we pass the heading text between the brackets to get_heading_url
, which first checks if it's the title of a page, and if so returns the page url. Otherwise it searches the markdown for a heading with the correct text and uses the markdown slugify
function to form the url.
The regex to find the heading in the markdown source is ^ *The Heading *$\n^[=-]+$|^#+ *The Heading *$
. The first half matches a Setext-style heading (the heading text, a newline, = or - signs) and the second half matches an ATX-style heading (1 or more # signs followed by the heading text).
Hope that makes sense. It's a bit hacky and slow, but it worked for me.
Hi, thanks again!
I eventually implemented this in my plugin, but maybe I'll get it out of it, in another plugin, at some point.
Here's what I did:
- in
on_page_content
, populate a mapping of all pages' anchors to their respective URLs - in
on_post_page
, make a soup, find all tags that are notcode
or child ofcode
, and that contains a[title][ref]
or[ref][]
markdown reference, and replace all these tags' contents with proper links using the anchor-URL mapping
See the commit here: mkdocstrings/mkdocstrings@bf946e7 😄
As a followup here,
mkdocstrings eventually got an even nicer implementation of this functionality, which is very performant and super reliable:
mkdocstrings/mkdocstrings#188
And later that functionality was moved into a standalone plugin:
https://github.com/mkdocstrings/autorefs
The functionality that it covers is the same as your plugin. So please consider adding a recommendation for that plugin to people arriving here.
(or, let me know if you want to hear about all the edge cases that we took into account :D)