Emphasis rules: delimiter runs and flanking

Markdown · Expert · 12 min

These rules explain every surprising asterisk and underscore, and why some inputs differ between parsers.

CommonMark's emphasis rules look complicated because they make ordinary text behave sensibly. The key idea is the delimiter run: a sequence of * or _ characters.

  • A run is left-flanking (can open) if it's not followed by whitespace, and either not followed by punctuation or preceded by whitespace or punctuation. Right-flanking (can close) is the mirror image.
  • So * not emphasis * stays literal: the runs are surrounded by spaces. 2 * 3 * 4 is safe for the same reason.
  • * can open and close inside words: un*believ*able. _ cannot open or close intraword, so snake_case_word is never emphasised. That's why underscores are safe in identifiers and * is preferred for intraword emphasis.

Matching uses a delimiter stack: closers look back for the nearest compatible opener. ***a*** becomes <em><strong>a</strong></em>. The rule of 3: when one of the runs can both open and close, a pair whose combined length is a multiple of 3 doesn't match unless both lengths are multiples of 3, which keeps *foo**bar**baz* parsing as intended.

Emphasis can't cross block boundaries, and code spans, links and autolinks take precedence: *[link*](url) doesn't put the link inside emphasis.

Older parsers (original Markdown.pl, some non-CommonMark libraries) differ exactly in these corners, so test tricky input with the renderer that matters.

Example

*emphasis*  _emphasis_  **strong**  __strong__
un*believ*able      -> un<em>believ</em>able
un_believ_able      -> un_believ_able   (no intraword _ emphasis)
snake_case_name     -> unchanged
2 * 3 * 4           -> unchanged (spaces around the delimiters)
* not emphasis *    -> a list item! (block structure first)
***both***          -> <em><strong>both</strong></em>
*foo**bar**baz*     -> <em>foo<strong>bar</strong>baz</em>
**unclosed          -> literal **unclosed

Remember

  • Delimiter runs must be left-flanking to open and right-flanking to close
  • _ never emphasises inside words; * does
  • Code spans and links take precedence over emphasis

Watch out for

  • Using _ for emphasis inside a word, as in re_use_able, and seeing literal underscores.

Check yourself

  1. How does CommonMark render file_name_here?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: spec.commonmark.org/0.31.2/#emphasis-and-strong-emphasis

Builds on

Unlocks

Nothing builds on this yet.