Sub topic 16
Diagrams with Mermaid and math expressions
This chapter assumes you can write fenced code blocks and headings in a README. It covers two GitHub features that look like code blocks but render as graphics: Mermaid diagrams and math.
Mermaid diagrams
Mermaid is a text-based diagramming language. You describe boxes and arrows in plain text, and GitHub draws the picture when it renders the page. To use it, open a fenced code block and set its language to mermaid. The diagram source goes inside.
Because the source is plain text, the diagram is versioned with your README. A reviewer sees a normal text diff when someone changes an arrow, instead of a binary image change.
The diagram below shows the flow of a typical README edit.
GitHub supports several Mermaid diagram types, including flowcharts, sequence diagrams, class diagrams, and Gantt charts. The first line of the source selects the type. A flowchart starts with flowchart TD (top to bottom) or flowchart LR (left to right). The spine's example uses the older graph TD form, which also works.
Common Mermaid errors
- A syntax error replaces the diagram. GitHub shows an error message in place of the picture. Fix the source and refresh.
- Special characters in labels break parsing. Wrap labels containing parentheses or quotes in double quotes, such as
A["Run (dev)"]. - Large diagrams become unreadable. Split one big diagram into several small ones.
- Other sites may not render it. Package registries that display your README often show the raw source instead of a picture.
Math expressions
GitHub renders LaTeX-style math. Wrap inline math in single dollar signs. Put display math, which sits on its own line, between double dollar signs.
The area of a circle is $A = \pi r^2$.
$$
\sum_{i=1}^{n} i = \frac{n(n+1)}{2}
$$
A price of \$5 stays as plain text.You can also use a code fence whose language is math for a display block. That form is useful when the math contains characters that Markdown would otherwise interpret, such as underscores.
Common math errors
- Stray dollar signs start math. Two
$characters in one paragraph can turn the text between them into a formula. Escape literal dollar signs as\$. - Invalid LaTeX shows an error. The formula is replaced by a red message, so preview before merging.
- Underscores and asterisks get read as emphasis. This happens when the formula is not delimited properly, so check that the delimiters are in place.
Exercise
Your README paragraph says "Plans cost $5 or $10 per month" and part of the sentence renders as a formula. What is the cause, and how do you fix it?
Show answer
The two dollar signs are read as the start and end of inline math. Escape each one with a backslash, writing \$5 and \$10, so they render as plain text.
Exercise
Which first line makes a Mermaid flowchart that runs left to right?
Show answer
flowchart LR