# Code Blocks

Course: [Markdown](https://www.devtutorials.ai/learn/markdown) · Section: Markdown Fundamentals
Source: https://www.devtutorials.ai/learn/markdown/fundamentals/code-blocks

> Show commands and code exactly as typed. Fix a code block that swallowed the page, write inline code and fenced blocks, add language hints, nest fences safely, and write commands people and agents can copy.

## The Code Block That Ate the Page

Asha adds a command to the order-support README. Below it, she writes the next section. On GitHub, the page looks strange:

````md runnable title="Everything after the command turned into code"
## Install

```bash
npm install

## Next steps

Read the [refund policy](docs/refunds.md).
````

Look at the Rendered tab. "Next steps" is not a heading. The link is not a link. Everything after `npm install` sits inside one grey code box, with the `##` and the brackets showing.

Asha opened a code block with three backticks, but never closed it. So Markdown treated the rest of the file as code. In this lesson, you will learn how code blocks open and close, and how to show code so that people, renderers and AI agents all read it exactly.

**In simple words:** a code block starts with three backticks and ends with three backticks. Everything between them is shown exactly as typed.

## TL;DR

- **Inline code** is code inside a sentence, wrapped in single backticks: `` `npm install` ``.
- A **code block** is code on its own lines. Start it with three backticks on a line, and end it with three backticks on a line.
- Put a **language hint** right after the opening backticks, like ` ```bash `. GitHub uses it to colour the code.
- Inside code, Markdown marks do nothing. `**`, `#` and `[ ]` show as typed.
- A code block that is never closed swallows the rest of the file.
- To show a code block inside a code block, use four backticks on the outside.

## A Real-World Example

Think about a recipe that says: "Type the oven code **180-FAN** on the panel."

The bold tells you to type those exact characters. You would not type "one hundred and eighty fan". You would not leave out the hyphen. Every character matters.

Code is the same. A command must be copied exactly, space for space. A code block tells every reader: "do not format this, do not change this, copy it as it is."

## What You Will Learn

In this lesson, you will learn:

1. How to write inline code inside a sentence.
2. How to write a fenced code block, and close it.
3. How to add a language hint.
4. How to show backticks and code fences inside code.
5. How an indent can turn text into code by accident.
6. How to write commands that people and AI agents can copy safely.

## Cheat Sheet

````md runnable title="Inline code and code blocks"
Run `npm install` before you start.

```bash
npm install
npm start
```

```json
{ "orderId": "A-1042", "status": "shipped" }
```

~~~
Tildes work too.
~~~
````

Change the code on the left. Notice that nothing inside a code block is ever formatted.

## Inline Code

### Code Inside a Sentence

**Inline code** is a short piece of code inside a normal sentence: a command, a file name, a setting. Wrap it in single backticks. The backtick is the key next to `1` on most keyboards.

```md runnable title="Inline code in a sentence"
Run `npm install`, then open `src/refunds.ts`.

Set `REFUND_DAYS` to `30`.

Without backticks: set REFUND_DAYS to 30, and call refund*order*total.

With backticks: set `REFUND_DAYS` to `30`, and call `refund*order*total`.
```

Open the HTML tab. Inline code becomes a `code` tag. Look at the last two lines. Without backticks, the stars made `order` italic. With backticks, the stars stay as stars. Markdown marks do nothing inside code.

**Use inline code for:** commands, file names, folder names, settings, function names and exact values a reader must type.

### Backticks Inside Inline Code

What if the code itself has a backtick? Wrap it in **two** backticks instead, with a space on each side.

```md runnable title="A backtick inside code"
Type `` `code` `` to show inline code.
```

The page shows one pair of backticks around the word `code`. The outer double backticks are the wrapper. The spaces next to them are dropped.

## Code Blocks

### Three Backticks to Open, Three to Close

A **code block** is code on its own lines. It is also called a **fenced code block**, because the backticks are like a fence around the code.

1. Put three backticks on a line by themselves.
2. Write the code on the next lines.
3. Put three backticks on a line by themselves to close it.

````md runnable title="A fenced code block"
To start the app:

```
npm install
npm start
```

The app opens on port 3000.
````

Open the HTML tab. The code block became a `pre` tag with a `code` tag inside. `pre` means "preformatted": every space and line break is kept.

Now delete the closing three backticks. The last sentence falls into the code block. That is what happened to Asha's README.

<Callout kind="warn">
An unclosed code block does not show an error. Everything after it, to the end of the file, becomes code. When a page suddenly looks grey and unformatted, look for an opening fence with no closing fence above that point.
</Callout>

### Tildes Work Too

You can use three tildes `~~~` instead of three backticks. The opening and closing fence must use the same character. Most people use backticks, so pick backticks unless you have a reason not to.

### The Language Hint

Right after the opening backticks, you can name the language of the code. This is the **language hint**, also called the info string.

````md runnable title="Language hints"
```bash
npm install
```

```json
{ "orderId": "A-1042", "status": "shipped" }
```

```js
const refundDays = 30;
```
````

Open the HTML tab. Each `code` tag got a class, such as `language-bash`. GitHub and most docs sites use that class to colour the code. The boxes in this course do not add colour, but the class is there for any renderer that does.

Common hints: `bash` or `sh` for terminal commands, `json`, `yaml`, `js`, `ts`, `python`, `csharp`, `html`, `css`, `sql`, `md`, and `text` for plain output.

<Callout kind="tip">
Always add a language hint, even `text`. It tells people and AI agents what they are looking at. A coding agent is far more likely to run a block marked `bash` as a command than an unmarked block it has to guess about.
</Callout>

## Code About Code

### Showing a Fence Inside a Fence

Sometimes you need to show a code block **inside** a code block. For example, a guide about Markdown that shows readers how to write a fence. This course does it all the time.

Three backticks inside the code would close the outer block too early. The fix: use **four** backticks for the outer fence. A fence only closes on a line with at least as many backticks as it opened with.

`````md runnable title="Four backticks around three"
````md
Here is how to show a command:

```bash
npm install
```
````
`````

The page shows one code block, with the inner three-backtick fence inside it as plain text. The four-backtick fence opened, and only a four-backtick line closed it.

### Code Inside a List

You saw this in the lists lesson: a code block inside a step must be indented to line up with the step's text. Otherwise the code block ends the list.

````md runnable title="A command inside a step"
1. Install the packages:

   ```bash
   npm install
   ```

2. Start the app.
````

## The Accidental Code Block

There is a second, older way to make a code block: indent every line by **four spaces**. It still works. And it causes accidents.

```md runnable title="Four spaces make code"
Refunds are allowed within 30 days.

    This line has four spaces in front.
```

The second line became a code block, just because of the spaces. This often happens when text is pasted from an email or a document with its own indent.

Use fenced code blocks for code. Remove leading spaces from normal text. Then you never get a code block you did not ask for.

<Callout kind="note">
Links do not work inside code either. A web address inside a code block is shown as text, and nobody can click it. If readers should open an address, put it in a normal sentence, outside the block.
</Callout>

## Code for People and Agents

People copy commands from docs. AI agents copy them too, and run them. A few habits make that safe.

| Habit | Why |
|---|---|
| One command per line | Each line can be copied and run on its own |
| No `$` prompt in front of commands | A copied `$ npm install` fails, because `$` is not part of the command |
| Commands and their output in separate blocks | A reader, or an agent, can copy the command without the output |
| A language hint on every block | The reader knows if it is a command, a config file or output |
| Exact names in inline code | `REFUND_DAYS` is clearly a name to type, not a word in the sentence |

````md runnable title="A command and its output"
Run the tests:

```bash
npm test
```

You should see:

```text
12 tests passed
```
````

The command block can be copied and run as it is. The output block is marked `text`, so nobody tries to run it.

## Where Code Is Used

- **README files:** install and run commands.
- **Docs sites:** examples in every programming language the product supports.
- **Agent files:** the exact build, test and lint commands an agent should run.
- **Bug reports:** the error message, copied exactly, in a `text` block.
- **Chat apps:** Slack, Teams and Discord all support backticks for code.

## Common mistakes

| Symptom | Cause | Fix |
|---|---|---|
| The rest of the page is one grey code box | A code block was opened and never closed | Add the closing three backticks |
| Stars or underscores in a name turned into italic | The name is not in backticks | Wrap it in `` ` `` |
| A normal paragraph shows as code | It starts with four spaces | Remove the spaces at the start of the line |
| An example fence closes the outer block early | Both fences use three backticks | Use four backticks for the outer fence |
| The code has no colours on GitHub | No language hint | Add the language after the opening backticks |
| A copied command fails with `$: command not found` | The block includes the `$` prompt | Remove the prompt from the code block |
| The list breaks around a command | The code block is not indented | Indent it to line up with the step's text |

## Quick Check

<Quiz items={[
  {
    q: "What happens if you open a code block and never close it?",
    options: ["Markdown shows an error", "Only the next line becomes code", "Everything to the end of the file becomes code", "The backticks are ignored"],
    answer: 2,
    why: "An open fence runs until a closing fence or the end of the file, so the rest of the page turns into code."
  },
  {
    q: "Where does the language hint go?",
    options: ["After the closing backticks", "Right after the opening backticks", "On the first line of code", "In a comment"],
    answer: 1,
    why: "The hint follows the opening fence on the same line, like ```bash. The renderer turns it into a language class."
  },
  {
    q: "How do you show a three-backtick fence inside a code block?",
    options: ["Escape each backtick", "Use four backticks for the outer fence", "Use bold", "You cannot"],
    answer: 1,
    why: "A fence closes only on a line with at least as many backticks as it opened with. Four on the outside lets three sit inside."
  },
  {
    q: "Why should you leave the $ prompt out of a command block?",
    options: ["It slows the command down", "It is not allowed in Markdown", "People and agents copy it, and the command then fails", "It changes the colour"],
    answer: 2,
    why: "The $ is shown by the terminal, not typed by you. A copied $ npm install is not a real command."
  }
]} />

## Exercises

<MdExercises items={[
  {prompt:"The code block is never closed, so the heading below it became code. Close the code block so `Next steps` is a real heading again.",starter:"## Install\n\n```bash\nnpm install\n\n## Next steps\n\nRead the refund policy.",solution:"## Install\n\n```bash\nnpm install\n```\n\n## Next steps\n\nRead the refund policy.",checks:[{"selector":"pre","count":1},{"selector":"pre code","text":"npm install"},{"selector":"h2","count":2},{"selector":"p","text":"Read the refund policy."}],hint:"Add a line with three backticks right after `npm install`.",explain:"A fence runs until a closing fence. With the closing backticks in place, the code block holds only the command, and the heading and paragraph after it are formatted again."},
  {prompt:"Add a language hint so renderers know this block is a terminal command.",starter:"```\nnpm install\nnpm start\n```",solution:"```bash\nnpm install\nnpm start\n```",checks:[{"selector":"pre code.language-bash","count":1},{"selector":"pre code","textContains":"npm start"}],hint:"Write `bash` right after the opening three backticks, on the same line.",explain:"The language hint follows the opening fence. The renderer turns it into the class `language-bash`, which GitHub uses to colour the code. `sh` would describe the code too, but this exercise asks for `bash`."},
  {prompt:"The stars in the function name turned `order` italic. Show `refund*order*total` exactly as typed, as inline code.",starter:"Call refund*order*total after each refund.",solution:"Call `refund*order*total` after each refund.",checks:[{"selector":"code","text":"refund*order*total"},{"selector":"em","exists":false}],hint:"Wrap the name in single backticks.",explain:"Markdown marks do nothing inside code. In backticks, the stars stay as stars and the name is shown exactly."}
]} />

## What to Remember

- Wrap commands, file names and exact values in single backticks: `` `npm install` ``.
- A code block opens with three backticks on a line and closes with three backticks on a line.
- An unclosed code block swallows the rest of the file.
- Add a language hint after the opening fence: `bash`, `json`, `js`, `text`.
- Use four backticks on the outside to show a three-backtick fence.
- Indent code blocks that belong to a list step. Avoid four-space indents for normal text.
- Keep commands copy-safe: one per line, no `$` prompt, output in its own `text` block.

## Further Reading

- [CommonMark: fenced code blocks](https://spec.commonmark.org/0.31.2/#fenced-code-blocks): how fences open and close.
- [CommonMark: code spans](https://spec.commonmark.org/0.31.2/#code-spans): the backtick rules for inline code.
- [GitHub Docs: creating and highlighting code blocks](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/creating-and-highlighting-code-blocks): language hints on GitHub.

Next: **Tables and Quotes**, where you build a comparison table, see where pipes and alignment break, and write quotes and divider lines.
