跳转至

代码高亮

MkDocs Material 提供了强大的代码高亮功能,支持 300+ 编程语言。

基础用法

使用三个反引号包裹代码块,并指定语言:

    ```python
    def hello():
        print("Hello, World!")
    ```

效果:

def hello():
    print("Hello, World!")

支持的语言

Python

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        return f"Hello, my name is {self.name}"

person = Person("Alice", 30)
print(person.greet())

JavaScript

// ES6+ 特性示例
const fetchData = async (url) => {
    try {
        const response = await fetch(url);
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error:', error);
        throw error;
    }
};

fetchData('https://api.example.com/data')
    .then(data => console.log(data));

TypeScript

interface User {
    id: number;
    name: string;
    email: string;
    isActive?: boolean;
}

class UserService {
    private users: User[] = [];

    addUser(user: User): void {
        this.users.push(user);
    }

    getUser(id: number): User | undefined {
        return this.users.find(u => u.id === id);
    }
}

Java

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");

        for (int i = 0; i < 5; i++) {
            System.out.println("Count: " + i);
        }
    }
}

Go

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, %s!", r.URL.Path[1:])
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

Rust

fn main() {
    let numbers = vec![1, 2, 3, 4, 5];

    let sum: i32 = numbers.iter()
        .filter(|&&x| x % 2 == 0)
        .sum();

    println!("Sum of even numbers: {}", sum);
}

SQL

SELECT 
    u.id,
    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.is_active = true
GROUP BY u.id, u.name, u.email
HAVING COUNT(o.id) > 5
ORDER BY order_count DESC;

YAML

# MkDocs 配置示例
site_name: My Documentation
theme:
  name: material
  palette:
    - scheme: default
      primary: indigo
      accent: indigo

nav:
  - Home: index.md
  - Getting Started:
    - Installation: installation.md
    - Usage: usage.md

JSON

{
    "name": "my-project",
    "version": "1.0.0",
    "description": "A sample project",
    "dependencies": {
        "express": "^4.18.0",
        "lodash": "^4.17.21"
    },
    "scripts": {
        "start": "node app.js",
        "test": "jest"
    }
}

Bash

#!/bin/bash

# 备份脚本
BACKUP_DIR="/backup/$(date +%Y%m%d)"
SOURCE_DIR="/home/user/documents"

echo "Starting backup..."
mkdir -p "$BACKUP_DIR"

tar -czf "$BACKUP_DIR/backup.tar.gz" "$SOURCE_DIR"

if [ $? -eq 0 ]; then
    echo "Backup completed successfully!"
else
    echo "Backup failed!"
    exit 1
fi

高级特性

行号

添加 linenums="1" 启用行号:

def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

print(factorial(5))  # 120

高亮特定行

使用 hl_lines 高亮指定行:

def calculate(x, y, operation):
    if operation == "add":
        return x + y  # 高亮
    elif operation == "subtract":
        return x - y
    elif operation == "multiply":
        return x * y  # 高亮
    else:
        raise ValueError("Unknown operation")

代码标题

bubble_sort.py
def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    return arr

代码注释

import numpy as np  # (1)

def normalize(data):  # (2)
    mean = np.mean(data)  # (3)
    std = np.std(data)
    return (data - mean) / std
  1. 导入 NumPy 库用于数值计算
  2. 定义归一化函数
  3. 计算数据的均值

代码组

使用标签页组织相关代码:

GET /api/users/123 HTTP/1.1
Host: api.example.com
Authorization: Bearer token123
Accept: application/json
{
    "id": 123,
    "name": "John Doe",
    "email": "john@example.com",
    "created_at": "2024-01-15T10:30:00Z"
}
{
    "error": "User not found",
    "code": 404,
    "message": "The requested user does not exist"
}