frostming / marko

A markdown parser with high extensibility.
https://marko-py.readthedocs.io/en/latest/
MIT License
345 stars 38 forks source link

MarkdownRenderer won't render Link elements #188

Closed sciencectn closed 6 months ago

sciencectn commented 7 months ago

I'm trying to turn some selected Link elements back into text. But MarkdownRenderer gives an error. Here's an example:

import marko
import marko.md_renderer
doc = marko.parse("[link](http://bouncingdvdlogo.com/)")
link = doc.children[0].children[0]
renderer = marko.md_renderer.MarkdownRenderer()
renderer.render(link)

and the output:

    140 link_title = (
    141     '"{}"'.format(element.title.replace('"', '\\"')) if element.title else None
    142 )
    143 assert self.root_node
    144 label = next(
    145     (
    146         k
--> 147         for k, v in self.root_node.link_ref_defs.items()
    148         if v == (element.dest, link_title)
    149     ),
    150     None,
    151 )
    152 if label is not None:
    153     if label == link_text:

AttributeError: 'Link' object has no attribute 'link_ref_defs'
sciencectn commented 7 months ago

Seems like these lines might have something to do with it: https://github.com/frostming/marko/blob/625f8a4373720d806286c7c8735ac4027e9dbd57/marko/renderer.py#L62-L63 They set the root_node to any Element but it seems like it should only be set to a Document.

Here's a workaround which is to set root_node manually:

import marko
import marko.md_renderer
doc = marko.parse("[link](http://bouncingdvdlogo.com/)")
link = doc.children[0].children[0]
renderer = marko.md_renderer.MarkdownRenderer()
renderer.root_node=doc
renderer.render(link)

Maybe we could throw an error if render_link is called and the root_node isn't set? Then drop these lines so root_node stays None then functions aren't tempted to access it. I tried dropping those lines, the tests still pass.