RingDotNetfor Ring

A project: Markdown to HTML

Write a small converter from the Markdown that people like to type into the HTML that browsers need — headings, paragraphs, lists, bold, italic, code and links — with regular expressions and a StringBuilder.

What you will learn#

Markdown in one minute#

Markdown is a way to write formatted text with plain characters: # Title is a heading, **bold**, *italic*, code between back-quotes, - item a list item, [text](address) a link. Many sites turn it into HTML.

The program#

samples/UsingDotNet/tutorials/ch02_markdown.ring
# a project - a small Markdown to HTML converter (regular expressions, StringBuilder, files)
load "dotnet.ring"

using {
	"System"
	"System.IO"
	"System.Text"
	"System.Text.RegularExpressions"
}

func main

	cMarkdown = "# Shopping" + nl +
		"" + nl +
		"Things to buy **today** for the *party*, see [the list](http://example.com/list)." + nl +
		"" + nl +
		"## Food" + nl +
		"- bread" + nl +
		"- cheese & `olives`" + nl +
		"- <fresh> fruit" + nl +
		"" + nl +
		"Thank you!"

	? "---- Markdown ----"
	? cMarkdown
	cHtml = markdownToHtml(cMarkdown)
	? nl + "---- HTML ----"
	? cHtml

	# save it as a complete page
	cFile = new Path().Combine([new Path().GetTempPath(),"ringdotnet_markdown.html"])
	new File().WriteAllText([ :path = cFile, :contents = "<html><body>" + nl + cHtml + nl + "</body></html>" ])
	? nl + "Saved a page of " + len(new File().ReadAllText(cFile)) + " characters"
	new File().Delete(cFile)

# The converter reads the text line by line and keeps a little state: are we inside a list?
func markdownToHtml cMarkdown

	oHtml = new StringBuilder("")
	lInList = False
	aLines = str2list(cMarkdown)
	for cLine in aLines
		cLine = trim(cLine)
		# an empty line ends a list and a paragraph
		if cLine = ""
			if lInList
				oHtml.AppendLine("</ul>")
				lInList = False
			ok
			loop
		ok
		# a list item starts with "- "
		if left(cLine,2) = "- "
			if not lInList
				oHtml.AppendLine("<ul>")
				lInList = True
			ok
			oHtml.AppendLine("<li>" + inlineHtml(substr(cLine,3)) + "</li>")
			loop
		but lInList
			oHtml.AppendLine("</ul>")
			lInList = False
		ok
		# headings: the number of # is the level
		if left(cLine,3) = "###"
			oHtml.AppendLine("<h3>" + inlineHtml(trim(substr(cLine,4))) + "</h3>")
		but left(cLine,2) = "##"
			oHtml.AppendLine("<h2>" + inlineHtml(trim(substr(cLine,3))) + "</h2>")
		but left(cLine,1) = "#"
			oHtml.AppendLine("<h1>" + inlineHtml(trim(substr(cLine,2))) + "</h1>")
		else
			oHtml.AppendLine("<p>" + inlineHtml(cLine) + "</p>")
		ok
	next
	if lInList
		oHtml.AppendLine("</ul>")
	ok
	return trim(oHtml.ToString())

# the formatting inside a line: FIRST make the text safe, THEN add our own tags
func inlineHtml cText

	# 1. escape: text typed by people must not become HTML (see the tutorial "A small web site")
	cSafe = substr(cText,"&","&amp;")
	cSafe = substr(cSafe,"<","&lt;")
	cSafe = substr(cSafe,">","&gt;")
	# Each step below writes its result to a new variable, and the next step reads it.
	# 2. code `x`
	cCode = new Regex("`([^`]+)`").Replace([ :input = cSafe, :replacement = "<code>$1</code>" ])
	# 3. bold **x** (before italic: it also uses the star)
	cBold = new Regex("\*\*(.+?)\*\*").Replace([ :input = cCode, :replacement = "<strong>$1</strong>" ])
	# 4. italic *x*
	cItalic = new Regex("\*(.+?)\*").Replace([ :input = cBold, :replacement = "<em>$1</em>" ])
	# 5. links [text](address)
	cLinks = new Regex("\[([^\]]+)\]\(([^)]+)\)").Replace([ :input = cItalic, :replacement = "<a href='$2'>$1</a>" ])
	return cLinks
Output
---- Markdown ----
# Shopping

Things to buy **today** for the *party*, see [the list](http://example.com/list).

## Food
- bread
- cheese & `olives`
- <fresh> fruit

Thank you!

---- HTML ----
<h1>Shopping</h1>

<p>Things to buy <strong>today</strong> for the <em>party</em>, see <a href='http://example.com/list'>the list</a>.</p>

<h2>Food</h2>

<ul>

<li>bread</li>

<li>cheese &amp; <code>olives</code></li>

<li>&lt;fresh&gt; fruit</li>

</ul>

<p>Thank you!</p>



Saved a page of 304 characters

How it works#

Two levels#

A document has blocks (headings, paragraphs, lists) and, inside the blocks, inline parts (bold, links). The program handles them separately:

Blocks: a scan with state#

The function goes through the lines. The one thing it must remember is whether it is inside a list: the first - line opens <ul>, further items continue it, and the first line that is not an item (or an empty line) closes it with </ul>. Headings are recognized by the number of #: check ### first, then ##, then #, otherwise the line is a paragraph. A StringBuilder collects the output without copying the text again and again.

Inline: escape first#

Warning

The first step of inlineHtml is to replace &, < and > by their HTML codes. Without it, a line such as - <fresh> fruit would produce a <fresh> tag that the browser tries to read, and a malicious document could contain a <script>. Escape first, then add your own tags, so the only tags in the output are yours. (The result in the output: &lt;fresh&gt; fruit.)

Inline: regular expressions#

PatternReplacementResult
a back-quote, some text, a back-quote<code>$1</code>code
\*\*(.+?)\*\*<strong>$1</strong>bold
\*(.+?)\*<em>$1</em>italic
\[([^\]]+)\]\(([^)]+)\)<a href='$2'>$1</a>link

$1 and $2 are the captured groups (the tutorial Regular expressions in depth); .+? is lazy so that two bold parts in one line are two separate matches. Bold before italic: both use the star, and **x** must be taken first.

Using objects during definition#

Look at how the steps are written: each result goes to a new variable (cSafe, cCode, cBold...), and the next step reads it. A step is one regular expression, so a new rule is one more line.

What you learned#

Exercises#

  1. Add numbered lists (1. item) and <ol>.
  2. Add > quote lines as <blockquote>.
  3. Add code blocks between three backticks lines.
  4. Read a .md file from disk and write the matching .html file.

Next#

A spell checker

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.