18. Reading inside a line

The blocks are ready. Now let's read the inside of a line, the emphasis and the code, and build the inlines of chapter 16.

Reading up to a marker

Emphasis and code start with a marker, and end with the same marker. upto(C, Cs) reads characters up to the next C, and gives the characters before it.

upto(C, []) --> [C], !.
upto(C, [X | Xs]) --> [X], upto(C, Xs).

For **, we need a version that looks for two markers in a row.

upto2(C, []) --> [C, C], !.
upto2(C, [X | Xs]) --> [X], upto2(C, Xs).

The cuts stop at the first marker that is found. Without them, Prolog could also try a later marker, and *a* and *b* could be read as one emphasis with a* and *b inside.

The inlines

inlines//1 tries the kinds of inlines in order.

inlines([]) --> eos, !.
inlines([strong(I) | Is]) --> ['*', '*'], upto2('*', Cs), { phrase(inlines(I), Cs) }, !, inlines(Is).
inlines([em(I) | Is]) --> ['*'], upto('*', Cs), { Cs \= [], phrase(inlines(I), Cs) }, !, inlines(Is).
inlines([code(A) | Is]) --> ['`'], upto('`', Cs), !, { atom_chars(A, Cs) }, inlines(Is).
inlines([text(A) | Is]) --> plain(Cs), { Cs \= [] }, !, { atom_chars(A, Cs) }, inlines(Is).
inlines([text(C) | Is]) --> [C], inlines(Is).

plain([C | Cs]) --> [C], { C \== '*', C \== '`' }, plain(Cs).
plain([]) --> [].
  • At the end of the line, there are no more inlines.
  • ** starts strong emphasis. The text up to the next ** is read again with inlines//1, so that it can hold code or emphasis too. This is recursion inside recursion.
  • * starts emphasis, in the same way. It must not be empty.
  • ` starts code. The code is not read again, because Markdown inside code is plain text.
  • Plain text is the longest run of characters without a marker. C \== '*' is true when C is not the same term as '*'. It is the opposite of == from chapter 10, and it never unifies.
  • If nothing else works, the character is text. This handles a * with no closing marker, such as in 2 * 3.

The order of the clauses matters here. ** must come before *, or **bold** would be read as an empty emphasis.

The third query shows code inside strong emphasis. The last one shows a lone * as text.

Blocks with inlines

Now replace atom_chars/2 in the block grammar of chapter 17 with inlines//1. The blocks get inlines instead of plain atoms, and the reader is complete.

The answer is the term that chapter 16 wrote by hand. The reader is done.

Try it

  1. Add links, [text](url), with the term link(Inlines, Url). Read the text up to ] with upto//2, then the URL up to ).
  2. snake_case_name is plain text in Markdown, but _text_ is emphasis. Add _ as another emphasis marker. Does snake_case_name still come out as plain text?
An unhandled error has occurred. Reload 🗙