1

I use Redcarpet to parse and render markdown, though I require some specific changes from the default behaviour. For example, although I do need autolink, I need it to not link anything formatted like an email address. To achieve this, I use this custom renderer class:

class HTMLRenderer < Redcarpet::Render::HTML
  def block_code(code, language)
    "<pre><code>#{encode(code).gsub("\n", "<br/>")}</code></pre>"
  end

  def autolink(link, link_type)
    return link if link_type == :email
    Formatter.instance.link_url(link)
  end

  private

  def html_entities
    @html_entities ||= HTMLEntities.new
  end

  def encode(html)
    html_entities.encode(html)
  end
end

The next adjustment I need to make is for it to not attempt to handle lists at all. That is, if I give it input in this form:

- element 1
- element 2
- element 3

What I don't want is:

  • element 1
  • element 2
  • element 3

I want it to leave the list untouched:

- element 1
- element 2
- element 3

First, I attempted to solve this very similarly to how I prevented emails from autolinking:

def list(contents, list_type)
  contents
end

def list_element(text, list_type)
  text
end

But in this case, if I give it the example list from before, I get this output:

element1element2element3

While I could work around this by simply adding the newlines back in and prepending "- " to each element, I want to preserve the specific character that was used to create the list, which could be any of -+* (or a number in the case of an ordered list).

So the conclusion I've drawn is that messing around in the renderer is the wrong solution; by the time text is being rendered, I've already lost the information I need. I think that what I should be looking into is changing the behaviour of the parser. Unfortunately, while documentation and examples of modifying renderer behaviour are abundant, I've found nothing of the sort for modifying parser behaviour beyond the supported flags.

How do I disable the parsing of a markdown feature entirely?

  • I feel your pain. In my case I want to implement [`start`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol#attr-start) attribute for ordered list. But overriding `list` and `list_item` doesn't allow me to read the given number. – sn3p Nov 09 '22 at 11:39

1 Answers1

0

I have found a solution, though I don't particularly like it.

def preprocess(document)
  document.gsub!(/^(\s*)(-|\+|\*) /, '\1\\\\\2 ')
  document.gsub(/^(\s*\d+)\. /, '\1\. ')
end

By using the preprocessor I can escape anything that will eventually become a list. I'd rather have a more robust solution, though.