Skip to content

Instantly share code, notes, and snippets.

@hyperionel
Last active March 17, 2017 18:35
Show Gist options
  • Save hyperionel/cd5b3cd77353379e63d16721aae239b2 to your computer and use it in GitHub Desktop.
Save hyperionel/cd5b3cd77353379e63d16721aae239b2 to your computer and use it in GitHub Desktop.
Commonmarker characteristics
# Commonmarker's default html renderer: https://github.com/gjtorikian/commonmarker/blob/master/lib/commonmarker/renderer/html_renderer.rb
# It has a sepparate method for each type of html tag it supports
# paragraph method:
def paragraph(node)
if @in_tight && node.parent.type != :blockquote
out(:children)
else
block do
container('<p>', '</p>') do
out(:children)
end
end
end
end
# We can override the header output by creating a custom renderer inheriting their default htmlrender
# https://github.com/gjtorikian/commonmarker#creating-a-custom-renderer
class MyHtmlRenderer < CommonMarker::HtmlRenderer
def initialize
super
@headerid = 1
end
def header(node)
block do
out("<h", node.header_level, " id=\"", @headerid, "\">",
:children, "</h", node.header_level, ">")
@headerid += 1
end
end
end
#For parsing something like #3232 and replacing it with a link we can go node by node to replace it
# https://github.com/gjtorikian/commonmarker#example-walking-the-ast
doc = CommonMarker.render_doc("# The site\n\n [GitHub](https://www.github.com) #3232 <ul><li>#3232</li></ul>")
doc.walk do |node|
if node.type == :text
if node.string_content.match(/ #[0-9]{1,4} /)
link_node = Node.new(:link)
link_node.url = "http://www.someurl.com"
link_node.first_child.string_content = "Whatever we want to call it"
node.insert_before(link_node)
node.delete
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment