Editor

Inline Markdown to HTML

#421 · Parsing · Advanced · 160 XP · about 35 min

Chat apps let people type **bold** or *italic* and show the message formatted. Write md_inline(text) that turns one line of Markdown into HTML with these rules:

  • Two asterisks on each side make bold text: **hi** becomes <strong>hi</strong>. Two asterisks next to each other always mean bold.
  • One asterisk on each side makes italic text: *hi* becomes <em>hi</em>.
  • A backtick on each side makes code: everything between the two backticks is copied as it is, with no formatting and no backslash escapes, between <code> and </code>.
  • [label](url) makes a link, <a href="url">label</a>. The label may contain bold, italic and code. The url runs up to the first ) and is copied as it is.
  • Bold and italic may contain each other, code and links.
  • A backslash in front of a backslash, a backtick, *, [, ], ( or ) stands for that character as plain text. A backslash in front of anything else is a plain backslash.
  • In everything that ends up as text, code and urls included, replace & with &amp;, < with &lt;, > with &gt;, a double quote with &quot; and a single quote with &#x27;. This is exactly what html.escape does.

Examples

md_inline('Some **bold** and *italic* text')
# returns 'Some <strong>bold</strong> and <em>italic</em> text'
md_inline('Run `x < 3 && y` first')
# returns 'Run <code>x &lt; 3 &amp;&amp; y</code> first'
md_inline('See [the **docs**](https://example.com/?a=1&b=2).')
# returns 'See <a href="https://example.com/?a=1&amp;b=2">the <strong>docs</strong></a>.'
md_inline('Price: 2 \\* 3 is *six*')
# returns 'Price: 2 * 3 is <em>six</em>'

In the last example the text holds a backslash before the first asterisk, so that asterisk is plain text.

Constraints

  • text has at most 100,000 characters and no line breaks.
  • The text is well formed: every bold, italic, code and link that opens is closed, inside the element around it, and elements nest at most 20 deep. Nothing is empty, and three asterisks in a row never appear.
  • Outside code, a ] that is not escaped always ends a link's label, and a url contains only letters, digits and the characters : / . ? = & # - _ %.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.