gjtorikian / commonmarker

Ruby wrapper for the comrak (CommonMark parser) Rust crate
MIT License
418 stars 81 forks source link

Using render options with a custom renderer #25

Closed evuez closed 8 years ago

evuez commented 8 years ago

I'm having a hard time trying to figure out a way to use the render options with a custom renderer. I inherited from CommonMarker::HtmlRenderer and customized some methods but now I can't find a way to do something like CustomRenderer.new.render_with_opts(doc, [:safe, :hardbreaks]).

Is it even possible? If it is could you help me with that?

Thanks!

gjtorikian commented 8 years ago

Is it even possible?

Unfortunately not. 😦

As you might have noticed, libcmark has two different types of options: parse options and render options. First a document is parsed to figure out the general structure, and then it's rendered into HTML. Since you're using a custom renderer, you have to be the one to define what to do when content is parsed.

The html_renderer class present in the gem gives the most barebones implementation possible. If I'm not mistaken, it actually defaults to doing safe already for you:

    def link(node)
      out('<a href="', node.url.nil? ? '' : escape_href(node.url), '"')
      if node.title && !node.title.empty?
        out(' title="', escape_html(node.title), '"')
      end
      out('>', :children, '</a>')
    end

A "non-safe" class that inherited from HtmlRenderer might instead choose to render links like this:

    def link(node)
      out('<a href="', node.url.nil? ? '' :node.url, '"')
      if node.title && !node.title.empty?
        out(' title="', node.title, '"')
      end
      out(' data-unsafe=true>', :children, '</a>')
    end

So basically, for the bits you'd like to change, you'd have to override the methods to do whatever you want them to. I hope this helps!

evuez commented 8 years ago

OK, thanks for the extensive answer!