Markdown Code
Displaying code in Markdown is a very common scenario, whether it's technical documentation, tutorials, or code examples. This chapter will detail various uses of code in Markdown.
Inline Code
Basic Syntax
Use a single backtick ` to wrap code:
This is a paragraph containing `console.log()`.Effect:
This is a paragraph containing console.log().
Multiple Phrases
Use the `git commit` command to commit code.
Use `const` and `let` to declare variables in JavaScript.Effect:
Use the git commit command to commit code. Use const and let to declare variables in JavaScript.
Including Special Characters
Special characters within backticks don't need escaping:
Use `*` to represent multiplication.
HTML tags `<div>` are block-level elements.Effect:
Use * to represent multiplication. HTML tags <div> are block-level elements.
Escaping Backticks
If the code itself contains backticks, use double backticks to wrap:
`` Use `code` to mark code ``Effect:
Use code to mark code
Code Blocks
Basic Code Block
Use three backticks ``` to create a code block:
function hello() { console.log("Hello, World!"); }
Effect:
function hello() {
console.log("Hello, World!");
}Indented Code Block
Using 4 spaces or 1 tab for indentation can also create a code block:
function hello() {
console.log("Hello, World!");
}Effect:
function hello() {
console.log("Hello, World!");
}
Syntax Highlighting
Specify Language
Add a language identifier after the three backticks to get syntax highlighting:
```python
def greet(name):
return f"Hello, {name}!"
**Effect:**
```python
def greet(name):
return f"Hello, {name}!"Common Language Identifiers
| Language | Identifier |
|---|---|
| JavaScript | javascript or js |
| Python | python or py |
| Java | java |
| C/C++ | c or cpp |
| Go | go |
| Rust | rust |
| Ruby | ruby |
| PHP | php |
| HTML | html |
| CSS | css |
| SQL | sql |
| Shell/Bash | bash or sh |
| JSON | json |
| YAML | yaml |
| Markdown | markdown or md |
Various Language Examples
JavaScript
const greet = (name) => {
return `Hello, ${name}!`;
};
console.log(greet("World"));Python
class Person:
def __init__(self, name):
self.name = name
def say_hello(self):
print(f"Hello, I'm {self.name}")
person = Person("Alice")
person.say_hello()HTML
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>Welcome</h1>
<p>This is a paragraph.</p>
</body>
</html>CSS
.container {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
.button {
background-color: #007bff;
color: white;
padding: 10px 20px;
border-radius: 5px;
}SQL
SELECT
id,
name,
email
FROM users
WHERE status = 'active'
ORDER BY created_at DESC;JSON
{
"name": "Zhang San",
"age": 30,
"skills": ["Python", "JavaScript", "Go"],
"address": {
"city": "Beijing",
"district": "Chaoyang District"
}
}YAML
database:
host: localhost
port: 5432
name: myapp
server:
port: 8080
mode: production
features:
- auth
- api
- cacheAdvanced Code Block Features
Line Numbers
Some editors support displaying line numbers:
```python {1,3-5}
def hello():
print("First line")
print("Second line")
print("Third line")
print("Fourth line")
print("Fifth line")
**Effect:**
```python {1,3-5}
def hello():
print("First line")
print("Second line")
print("Third line")
print("Fourth line")
print("Fifth line")Code Block Title
```python title="greet.py"
def greet(name):
print(f"Hello, {name}!")
### Collapsible Code Block
```markdown
```python fold
def long_function():
# Lots of code
pass
## Special Character Handling
### Escaping Backticks
In inline code, if the code contains backticks:
```markdown
Use `` `code` `` to mark code.Effect:
Use `code` to mark code.
Use HTML Entities
Use <div> to create a div element.Effect:
Use <div> to create a div element.
Code Block Best Practices
1. Always Specify Language
```python
def hello():
print("Hello")
Specifying language gives syntax highlighting and better readability.
### 2. Keep Code Concise
Choose the most representative code snippets, avoid overly long code blocks.
### 3. Add Comments
```markdown
```python
# Calculate Fibonacci sequence
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
### 4. Use Consistent Indentation
Maintain consistent code indentation style.
### 5. Avoid Overly Long Lines
```markdown
```python
# Not recommended
result = some_long_function_name(argument1, argument2, argument3, argument4, argument5)
# Recommended
result = some_long_function_name(
argument1,
argument2,
argument3
)
## Code Block Layout in Documents
### Between Paragraphs
```markdown
This is a paragraph.
```python
print("code block")This is another paragraph.
### In Lists
```markdown
- Item 1
- Item 2 (contains code):
```python
def hello():
print("Hello")- Item 3
**Effect:**
- Item 1
- Item 2 (contains code):
```python
def hello():
print("Hello")- Item 3
In Blockquotes
> This is a blockquote:
>
> ```python
> print("code in quote")
> ```Effect:
This is a blockquote:
pythonprint("code in quote")
Keyboard Shortcuts
Use HTML tags to display keyboard shortcuts:
<kbd>Ctrl</kbd> + <kbd>C</kbd>
<kbd>Cmd</kbd> + <kbd>S</kbd>
<kbd>Shift</kbd> + <kbd>Enter</kbd>Effect:
Ctrl + CCmd + SShift + Enter
Code Block Export and Sharing
GitHub Gist
Share code as Gist, then embed in Markdown:
```js gist:1234567890
### External Links
```markdown
View complete code: [GitHub repository](https://github.com/username/repo)Code Support on Different Platforms
GitHub/GitLab
- Full syntax highlighting support
- Supports multiple languages
- Auto-detects language
Notion
- Basic syntax highlighting
- Supports common languages
- Can copy code blocks
VS Code
- Use plugins to preview Markdown
- Full syntax highlighting
- Supports custom themes
Typora
- Real-time preview
- Complete syntax highlighting
- Switchable code themes
Practical Examples
Technical Documentation
## Install Dependencies
Use npm to install necessary packages:
```bash
npm install express mongoose corsConfigure Application
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(3000);
### Code Comparison
```markdown
### Old Version
```javascript
function hello(name) {
return "Hello " + name;
}New Version
const hello = (name) => `Hello ${name}`;
## Summary
This chapter detailed code display methods in Markdown:
- **Inline code**: Use single backtick
- **Code blocks**: Use three backticks
- **Syntax highlighting**: Implemented through language identifiers
- **Advanced features**: Line numbers, titles, collapsing, etc.
- **Best practices**: Specify language, keep concise, add comments
Mastering code blocks will make your technical documentation more professional and readable.
**Next:** Learn how to use [Markdown Links](./links).