Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Markdown Code

Markdown Code

Markdown provides multiple ways to display code, from simple inline code to complex code blocks, meeting different code-display needs.


Inline code

If it is a function or a snippet of code in a paragraph, you can wrap it with backticks (`), for example:

`printf()` 函数

The display result is as follows:

Common usage examples:

Escaping special characters

When you need to display a backtick or other special characters in inline code, escape handling is required.

Ways to display a backtick:

** Surround a single backtick with double backticks: **



``使用 `反引号` 包围代码``

Rendered effect:

Surround with multiple backticks:



```包含 `` 双反引号的代码```

Rendered effect:

Other special character handling:


Code blocks

Indented code blocks

Code blocks use 4 spacesor atab character (Tab key).

Syntax format:



正常文本段落



    这是缩进式代码块

    每行前面有四个空格

    保持代码的原始格式

    

继续正常文本

The example is as follows:

The display result is as follows:

Triple-backtick code blocks

You can also wrap a block of code with ``` and specify a language (or not):

Multi-line code content can include blank lines and keep its original indentation

Triple backticks (```) are the most commonly used code block syntax, supporting syntax highlighting and multi-line code display.

```javascript

$(document).ready(function () {

    alert('RUNOOB');

});



The results are displayed as follows:



![](https://www.runoob.com/wp-content/uploads/2019/03/88F52386-2F98-4D7E-8935-E43BECA6D868.jpg)



Notes:



- 缩进式代码块前后需要空行分隔

- 所有代码行必须保持一致的缩进

- 不支持语法高亮

- 在列表中使用时需要8个空格缩进



### 语言标识和语法高亮



在三反引号后添加语言标识符可以启用语法高亮功能。



List of common language identifiers:



- `javascript` / `js` - JavaScript

- `python` / `py` - Python

- `html` - HTML

- `css` - CSS

- `sql` - SQL

- `json` - JSON

- `xml` - XML

- `yaml` / `yml` - YAML

- `bash` / `shell` - Shell脚本

- `java` - Java

- `cpp` / `c++` - C++

- `csharp` / `c#` - C#

- `php` - PHP

- `ruby` / `rb` - Ruby

- `go` - Go语言

- `rust` - Rust

- `typescript` / `ts` - TypeScript



**JavaScript:**



const users = [

    { name: "Alice", age: 25 },

    { name: "Bob", age: 30 }

];



const adults = users.filter(user => user.age >= 18);

console.log(adults);



**Python:**



def calculate_area(radius):

    """计算圆的面积"""

    import math

    return math.pi * radius ** 2



# Use function

area = calculate_area(5)

print(f"圆的面积是: {area:.2f}")



**SQL:**



SELECT u.name, u.email, COUNT(o.id) as order_count

FROM users u

LEFT JOIN orders o ON u.id = o.user_id

WHERE u.created_at >= '2024-01-01'

GROUP BY u.id, u.name, u.email

ORDER BY order_count DESC

LIMIT 10;



![](https://www.runoob.com/wp-content/uploads/2019/03/e819b3a7-4406-45b4-8772-c67bbe422bd0-1.png)



---



## Advanced Code Block Features



### Line Number Display



某些 Markdown 渲染器支持显示行号,通过特定的语法或配置实现。



Syntax examples (partial support):



function fibonacci(n) {

    if (n <= 1) return n;

    return fibonacci(n - 1) + fibonacci(n - 2);

}



console.log(fibonacci(10));



![](https://www.runoob.com/wp-content/uploads/2019/03/813e23c9-7923-47cd-b6a6-a1536a55da67.png)



Or use:



const numbers = [1, 2, 3, 4, 5];

const doubled = numbers.map(x => x * 2);

const sum = doubled.reduce((a, b) => a + b, 0);

console.log(`总和: ${sum}`);



### 代码差异对比



用于显示代码的添加、删除或修改,常用于展示版本控制中的变更。



Diff Syntax:



function calculateTotal(items) {

-   let total = 0;

+   let total = 0.0;

    

    for (let item of items) {

-       total += item.price;

+       total += parseFloat(item.price);

    }

    

+   // 保留两位小数

+   total = Math.round(total * 100) / 100;

    return total;

}



![](https://www.runoob.com/wp-content/uploads/2019/03/653e1bce-e2d7-4c8b-8329-7b5ecfef3807.png)



Git-style diff display:



@@ -1,5 +1,8 @@

 function greetUser(name) {

-    console.log("Hello " + name);

+    if (!name) {

+        throw new Error("Name is required");

+    }

+    console.log(`Hello, ${name}!`);

 }



Language-specific differences comparison:



// 之前的代码

const oldFunction = () => {

    var x = 10;  // ❌ 使用 var

    console.log("Value: " + x);  // ❌ 字符串拼接

}



// Improved code

const newFunction = () => {

    const x = 10;  // ✅ 使用 const

    console.log(`Value: ${x}`);  // ✅ 模板字符串

}



![](https://www.runoob.com/wp-content/uploads/2019/03/3ba07b77-1570-48b8-86dd-a041a52ece21.png)