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 * 4is safe for the same reason. *can open and close inside words:un*believ*able._cannot open or close intraword, sosnake_case_wordis 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 **unclosedRemember
- 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.