16. The document as a term

The second goal is a converter from Markdown to HTML. It takes this text

# Learn Prolog

Prolog turns **Markdown** into *HTML*.

- write `a < b` safely
- in a few rules

and gives this HTML.

<h1>Learn Prolog</h1>
<p>Prolog turns <strong>Markdown</strong> into <em>HTML</em>.</p>
<ul><li>write <code>a &lt; b</code> safely</li><li>in a few rules</li></ul>

The plan

The converter works in two steps, like a compiler.

  1. Read. A grammar reads the Markdown text, and builds a term that describes the document. Chapters 17 and 18 write this part.
  2. Write. Another grammar takes the term, and writes HTML. Chapter 19 writes this part.

The term in the middle is the key. Once the document is a term, it is easy to check it, change it, or write it in another format. In this chapter, we decide its shape, and practice working with it.

The parts we support

We support a small part of Markdown.

Markdown Meaning
# Title to ###### Title A heading of level 1 to 6
Lines of text A paragraph. Lines next to each other belong to the same paragraph.
- item An item of a list. Lines next to each other belong to the same list.
An empty line The end of a paragraph or a list
**text** Strong emphasis
*text* Emphasis
`text` Code

The shape of the term

A document is a list of blocks.

  • h(Level, Inlines) is a heading.
  • p(Inlines) is a paragraph.
  • ul(Items) is a list. Each item is a list of inlines.

The content of a block is a list of inlines.

  • text(Atom) is plain text.
  • code(Atom) is code.
  • strong(Inlines) and em(Inlines) are emphasis. They hold more inlines, because emphasis can contain code or other emphasis.

So the Markdown above becomes this term.

[ h(1, [text('Learn Prolog')]),
  p([text('Prolog turns '), strong([text('Markdown')]), text(' into '), em([text('HTML')]), text('.')]),
  ul([ [text('write '), code('a < b'), text(' safely')],
       [text('in a few rules')] ])
]

It is the same kind of tree as the DOM of a web page, or the AST that a compiler builds.

Working with the term

Before we read any Markdown, let's write the term by hand, and ask questions about it. These predicates are a good warm up for the recursion in the next chapters.

plain_text(Inlines, Text) gives the text of some inlines, without any formatting.

The second query makes a table of contents. It is a findall/3 over the blocks of the document, as in chapter 10. The term is plain data, so all the tools of Prolog work on it.

inline_text/2 and plain_text/2 call each other. This is how you walk a tree with two kinds of nodes. Each kind has its own predicate.

Try it

  1. Write count_code(Doc, N), which counts the code(_) inlines in all paragraphs and headings of the document. Ignore the list items at first.
  2. Write headings_only(Doc, Hs), which gives the list of the headings of the document, with the other blocks removed.
An unhandled error has occurred. Reload 🗙