Sub topic 6
Inline code and fenced code blocks
This chapter assumes you can edit a Markdown file on GitHub and know the basics of headings and paragraphs. Code formatting is what lets a README show exact commands and file names without the renderer altering them.
Inline code
Wrap a short piece of code in single backticks. GitHub renders it in a monospace font and does not interpret Markdown inside it. Use it for file names, commands, option names, and values such as npm install, config.json, or "localhost".
To show a literal backtick, use a longer delimiter. Start and end the span with two backticks and put a space inside each end. Writing `` code ` displays code `.
Fenced code blocks
A fenced code block holds several lines of code. It opens with a line of three backticks and closes with a line of three backticks. Tildes (~~~) also work. The closing fence must use the same character and be at least as long as the opening fence.
Put a language identifier right after the opening fence. GitHub uses it to apply syntax highlighting. For example, a block opened with ``` `bash ``` renders as shell code:
git clone https://github.com/OWNER/REPO.git
cd REPO
npm installA block opened with ``` `json ``` renders as JSON:
{
"port": 3000,
"host": "localhost"
}The next table lists identifiers you will use often in READMEs.
| Identifier | Use it for |
|---|---|
| `bash` or `sh` | Shell commands |
| `json` | Configuration and API responses |
| `python`, `js` | Source code samples |
| `diff` | Changes, with `+` and `-` line prefixes |
| `text` | Plain output with no highlighting |
If you omit the identifier, or use one GitHub does not recognize, the block still renders as monospace text without colors.
- "port": 3000
+ "port": 8080To show a fence inside a block, open the outer block with four backticks. The outer block then ends only at a line of four or more backticks.
Common errors
- Missing closing fence. Everything after the opening fence renders as code, so the rest of the page looks broken.
- Shorter closing fence. A closing fence shorter than the opening one does not close the block.
- Copying the prompt. Leave
$out of install commands so readers can paste them directly. - Indented code. Indenting a line by four spaces also makes a code block, but it cannot carry a language label. Prefer fences.
Exercise
A README's install section stops highlighting partway through, and every heading after it appears in monospace. What is the most likely cause, and how do you fix it?
Show answer
The fenced block is missing its closing fence, so the renderer treats the rest of the file as code. Add a closing line of three backticks, using the same character and at least the same length as the opening fence.