Markdown: Markdown Code Syntax and Code Blocks
Code is the heart of technical documentation—Markdown provides an elegant way to present it so readers can both read and run it.
1. What You'll Learn
- Inline code syntax and use cases
- Fenced code blocks and syntax highlighting
- Writing correct language tags for code blocks
- Escaping and handling special characters in code blocks
- Embedding code inside lists and blockquotes
2. A Developer's Real Story
(1) Pain Point: Readers' Copied Code Throws Errors
Nina published Python tutorials on her tech blog, but readers complained that copying and running the code threw errors. Upon investigation, she found that her blogging platform's code blocks had no syntax highlighting—commas and periods looked identical, and some people copied ( as ( (full-width parentheses). Worse, some code blocks had no language label, so code appeared without any color differentiation.
(2) Solution: Standardize Code Block Formatting
Nina switched to fenced code blocks with proper language tags, and she tested every code snippet in a real environment before publishing. She also added a "Copy Code" button. After the switch, reader error reports dropped by 90%. Her blog gained recognition from multiple tech media outlets thanks to its highly reproducible code samples.
3. Inline Code
(1) Basic Syntax
Wrap text in a single backtick ` to create inline code:
Use the `print()` function to output text.
Run `npm install express` in the terminal.
The `<div>` tag is the most basic container in HTML.
| Scenario | Syntax | Effect |
|---|---|---|
| Function name | Call the `calculateTotal()` function |
Call the calculateTotal() function |
| Keyboard shortcut | Press `Ctrl+S` to save |
Press Ctrl+S to save |
| Filename | Edit the `.env` file |
Edit the .env file |
| Command | Run `git status` |
Run git status |
(2) Special Characters in Inline Code
To display a backtick itself, wrap it with double backticks:
Use `` ` `` to represent the backtick character.
In a sentence, use `code` and `` `backtick` `` together.
▶ Example: Correct Usage of Inline Code
In the file utils/helpers.py, a format_date() function is defined.
Pass a datetime object to it and it returns a formatted string.
Press F5 to refresh the page.
** won't make it bold. This ensures the code is presented exactly as written.
4. Fenced Code Blocks
(1) Basic Syntax
Wrap a code block with triple backticks ``` and optionally specify a language tag for syntax highlighting:
```python
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
```
(2) The Role of Language Tags
| Tag | Language | Example Filename |
|---|---|---|
python |
Python | main.py |
javascript |
JavaScript | app.js |
html |
HTML | index.html |
css |
CSS | style.css |
bash |
Terminal Commands | (none) |
json |
JSON | package.json |
markdown |
Markdown | README.md |
text |
Plain Text Output | (no highlighting) |
# Python code with syntax highlighting
def fibonacci(n):
"""Compute the nth term of the Fibonacci sequence"""
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(10)) # Output: 55
5. Indented Code Blocks
Besides fenced code blocks, Markdown also supports indented code blocks. Indent each line by 4 spaces or 1 tab:
This is a paragraph.
// 4-space indent turns this into a code block
function hello() {
console.log("Hello!");
}
Back to normal text.
```)—they are more powerful and clearer.
▶ Example: Fenced vs Indented Code Blocks
Fenced code blocks use triple backticks and support language tags and syntax highlighting.
Indented code blocks use 4 spaces at the start of a line, have good compatibility but no syntax highlighting.
Use fenced code blocks whenever possible.
6. Special Handling in Code Blocks
(1) Escaping Backticks in Code Blocks
If your code itself contains triple backticks, wrap it with more backticks:
````text
```python
print("Hello")
```
````
```` (four backticks), so the inner ``` is displayed as plain text.
(2) Wrapping Long Lines of Code
# Recommended: keep each line within 80 characters
const result = await api.getUserData(userId)
.then(data => processData(data))
.catch(error => handleError(error));
# Avoid: unwrapped super-long lines
const result = await api.getUserData(userId).then(data => processData(data)).catch(error => handleError(error));
▶ Example: Common Error Markers in Code Blocks
❌ Wrong approach:
Code blocks without language tags show as black text on white background
✅ Right approach:
Code blocks with a python language tag display colorful syntax highlighting
7. Embedding Code in Lists and Blockquotes
(1) Code Blocks inside Lists
Code blocks inside lists need an extra 8-space indent (or two tabs):
- Run the tests:
npm test -- --coverage
- Check formatting:
npx eslint src/ --fix
(2) Code Blocks inside Blockquotes
> **Key implementation:**
>
> ```python
> def process_data(df):
> return df.dropna().groupby("category").sum()
> ```
>
> The above code cleans null values and then groups and summarizes.
8. Complete Example: A Code Documentation Page
Data Processing Script Overview
Install dependencies: pip install pandas numpy matplotlib
load_data() function: loads data from a CSV file
clean_data() function: removes null values and duplicate rows
Full workflow:
1. Load data - load_data("sales.csv")
2. Clean - clean_data(data)
3. Output stats - print row count and column names
Expected result: A clean technical document with code and explanations alternating smoothly, correct language tags, and a clear division of labor between inline code and code blocks.
❓ FAQ
📖 Summary
- Inline code uses a single backtick; code blocks use triple backticks
- Always add a language tag to code blocks for syntax highlighting
- Indented code blocks (4 spaces) are no longer recommended—prefer fenced style
- Code blocks inside lists need extra indentation
- Escape backticks inside code blocks by wrapping with more backticks
- All indentation and whitespace in code blocks is fully preserved
📝 Exercises
-
Basic: Write a Markdown section that includes 3 inline code snippets (filename, function name, keyboard shortcut) and 1 code block with a language tag.
-
Intermediate: Create a nested structure in your Markdown document—embed a code block inside an unordered list item, and embed a code block inside a blockquote.
-
Challenge: Write a Markdown section with three levels of backtick nesting (demonstrating how to show a code block that itself shows a code block), and use four backticks for the outer wrapper to ensure correct rendering.