📢 新文章推送 · 每周更新优质内容 · 订阅更新 →
向下滚动
技术笔记

代码高亮测试 - 多语言代码块

AI 智能总结

本文用于测试代码块对各种编程语言的语法高亮支持。每种语言的代码块右上角应显示复制按钮,点击可一键复制代码。

1. Bash / Shell

 1#!/bin/bash
 2
 3# 连接 SSH 服务器
 4ssh user@192.168.1.1 -p 22
 5
 6# 常用命令
 7echo "Hello, World!"
 8pwd
 9ls -la /home/user/
10grep -r "keyword" ./src/
11
12# 循环示例
13for i in {1..10}; do
14    echo "Count: $i"
15done
16
17if [ -f "file.txt" ]; then
18    echo "File exists"
19fi

2. HTML

 1<!DOCTYPE html>
 2<html lang="zh-CN">
 3<head>
 4    <meta charset="UTF-8">
 5    <meta name="viewport" content="width=device-width, initial-scale=1.0">
 6    <title>测试页面</title>
 7    <link rel="stylesheet" href="style.css">
 8</head>
 9<body>
10    <header class="site-header">
11        <nav>
12            <a href="/" class="logo">My Blog</a>
13            <ul class="nav-menu">
14                <li><a href="/about/">关于</a></li>
15                <li><a href="/archives/">归档</a></li>
16            </ul>
17        </nav>
18    </header>
19
20    <main class="container">
21        <article class="post-content">
22            <h1>Hello World</h1>
23            <p>这是一个测试段落。</p>
24            <!-- 注释 -->
25            <div id="app"></div>
26        </article>
27    </main>
28
29    <script src="main.js"></script>
30</body>
31</html>

3. CSS

 1/* CSS 变量与主题 */
 2:root {
 3    --primary-color: #3b82f6;
 4    --bg-dark: #0f0f1a;
 5    --text-color: #1a1a2e;
 6    --border-radius: 8px;
 7    --transition: 0.3s ease;
 8}
 9
10/* 深色模式 */
11[data-theme="dark"] {
12    --bg-primary: #0f0f1a;
13    --text-primary: #e8e8f0;
14}
15
16/* 代码块样式 */
17.code-wrapper {
18    position: relative;
19    margin: 1em 0;
20}
21
22.code-wrapper pre {
23    padding: 20px 16px 12px;
24    background: #282c34;
25    border-radius: var(--border-radius);
26    overflow-x: auto;
27}
28
29.code-copy-btn {
30    position: absolute;
31    top: 8px;
32    right: 10px;
33    cursor: pointer;
34}
35
36/* 响应式布局 */
37@media (max-width: 768px) {
38    .container {
39        width: 100%;
40        padding: 0 16px;
41    }
42}

4. JavaScript

 1// ES6+ JavaScript 示例
 2const CodeBlock = {
 3    init() {
 4        const blocks = document.querySelectorAll('.post-content pre');
 5        if (!blocks.length) return;
 6
 7        blocks.forEach(pre => {
 8            const codeEl = pre.querySelector('code');
 9            if (!codeEl) return;
10
11            // 创建包装器和复制按钮
12            const wrapper = document.createElement('div');
13            wrapper.className = 'code-wrapper';
14
15            const btn = document.createElement('button');
16            btn.className = 'code-copy-btn';
17            btn.innerHTML = '<svg>...</svg><span>Copy</span>';
18
19            btn.addEventListener('click', async () => {
20                try {
21                    await navigator.clipboard.writeText(codeEl.textContent);
22                    btn.classList.add('copied');
23                    setTimeout(() => btn.classList.remove('copied'), 2000);
24                } catch (err) {
25                    console.error('Copy failed:', err);
26                }
27            });
28
29            pre.parentNode.insertBefore(wrapper, pre);
30            wrapper.appendChild(pre);
31            wrapper.appendChild(btn);
32        });
33    }
34};
35
36// 异步函数与 Promise
37async function fetchData(url) {
38    const response = await fetch(url);
39    if (!response.ok) throw new Error(`HTTP ${response.status}`);
40    return response.json();
41}
42
43// 解构赋值、箭头函数、模板字符串
44const { name, age } = person;
45const greet = (name) => `Hello, ${name}!`;
46
47// 类与继承
48class BlogPost {
49    #privateField; // 私有字段
50
51    constructor(title, content) {
52        this.title = title;
53        this.content = content;
54        this.createdAt = new Date();
55    }
56
57    get summary() {
58        return this.content.slice(0, 100) + '...';
59    }
60
61    static fromJSON(json) {
62        return new BlogPost(json.title, json.content);
63    }
64}

5. Python

 1#!/usr/bin/env python3
 2"""Python 代码块测试示例"""
 3
 4import asyncio
 5from dataclasses import dataclass
 6from typing import List, Optional
 7from datetime import datetime
 8
 9
10@dataclass
11class Article:
12    """文章数据类"""
13    title: str
14    content: str
15    tags: List[str]
16    published: bool = False
17    created_at: Optional[datetime] = None
18
19
20class BlogEngine:
21    """博客引擎类"""
22
23    def __init__(self, name: str):
24        self.name = name
25        self._articles: List[Article] = []
26
27    def add_article(self, article: Article) -> None:
28        """添加文章"""
29        article.created_at = datetime.now()
30        self._articles.append(article)
31        print(f"✅ 文章已添加: {article.title}")
32
33    async def publish_all(self) -> None:
34        """异步发布所有文章"""
35        for article in self._articles:
36            await asyncio.sleep(0.1)
37            article.published = True
38            print(f"📝 已发布: {article.title}")
39
40
41# 列表推导式、生成器、装饰器
42def cache(func):
43    _cache = {}
44    def wrapper(*args):
45        if args not in _cache:
46            _cache[args] = func(*args)
47        return _cache[args]
48    return wrapper
49
50
51@cache
52def fibonacci(n: int) -> int:
53    """斐波那契数列"""
54    if n <= 1:
55        return n
56    return fibonacci(n - 1) + fibonacci(n - 2)
57
58
59# 主程序入口
60if __name__ == "__main__":
61    blog = BlogEngine("Lumin Blog")
62
63    post = Article(
64        title="Python 高级特性",
65        content="数据类、异步、类型注解...",
66        tags=["python", "tutorial"]
67    )
68
69    blog.add_article(post)
70
71    # 输出斐波那契数列
72    fibs = [fibonacci(i) for i in range(10)]
73    print(f"斐波那契前10项: {fibs}")

6. Go (Golang)

 1package main
 2
 3import (
 4	"context"
 5	"encoding/json"
 6	"fmt"
 7	"log"
 8	"net/http"
 9	"time"
10)
11
12// Article 文章结构体
13type Article struct {
14	ID        int       `json:"id"`
15	Title     string    `json:"title"`
16	Content   string    `json:"content"`
17	Tags      []string  `json:"tags"`
18	CreatedAt time.Time `json:"created_at"`
19	Published bool      `json:"published"`
20}
21
22// Blog 博客引擎
23type Blog struct {
24	name     string
25	articles []Article
26}
27
28func NewBlog(name string) *Blog {
29	return &Blog{name: name}
30}
31
32func (b *Blog) AddArticle(a Article) {
33	a.CreatedAt = time.Now()
34	b.articles = append(b.articles, a)
35	fmt.Printf("✅ 已添加: %s\n", a.Title)
36}
37
38// Handler HTTP 处理器
39func (b *Blog) Handler(w http.ResponseWriter, r *http.Request) {
40	ctx := context.Background()
41	w.Header().Set("Content-Type", "application/json")
42
43	data, err := json.Marshal(b.articles)
44	if err != nil {
45		http.Error(w, err.Error(), http.StatusInternalServerError)
46		return
47	}
48
49	select {
50	case <-ctx.Done():
51		log.Println("请求已取消")
52	case w.Write(data):
53	}
54}
55
56// Channel 与 Goroutine 示例
57func processArticles(articles []Article, workers int) <-chan string {
58	ch := make(chan string, len(articles))
59	sem := make(chan struct{}, workers)
60
61	for _, a := range articles {
62		sem <- struct{}{}
63		go func(art Article) {
64			defer func() { <-sem }()
65			time.Sleep(100 * time.Millisecond)
66			ch <- fmt.Sprintf("已处理: %s", art.Title)
67		}(a)
68	}
69	return ch
70}
71
72func main() {
73	blog := NewBlog("Lumin Blog")
74	blog.AddArticle(Article{
75		Title:   "Go 并发编程",
76		Content: "Goroutine、Channel...",
77		Tags:    []string{"go", "concurrency"},
78	})
79
80	http.HandleFunc("/", blog.Handler)
81	log.Println("服务器启动于 :8080")
82	log.Fatal(http.ListenAndServe(":8080", nil))
83}

7. SQL

 1-- MySQL / PostgreSQL 示例
 2CREATE TABLE IF NOT EXISTS `articles` (
 3    `id` INT AUTO_INCREMENT PRIMARY KEY,
 4    `title` VARCHAR(255) NOT NULL COMMENT '文章标题',
 5    `content` TEXT COMMENT '文章内容',
 6    `category` VARCHAR(50) DEFAULT 'tech' COMMENT '分类',
 7    `tags` JSON COMMENT '标签数组',
 8    `view_count` INT DEFAULT 0 COMMENT '阅读量',
 9    `is_published` TINYINT(1) DEFAULT 0,
10    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
11    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
12    INDEX `idx_category` (`category`),
13    INDEX `idx_created` (`created_at` DESC),
14    FULLTEXT INDEX `ft_title_content` (`title`, `content`)
15) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
16
17-- 插入数据(含子查询)
18INSERT INTO articles (title, content, category, tags, is_published)
19VALUES (
20    'SQL 性能优化指南',
21    '索引策略、查询优化...',
22    'tech',
23    JSON_ARRAY('mysql', 'database', 'performance'),
24    1
25);
26
27-- 复杂查询:JOIN + 窗口函数 + CTE
28WITH monthly_stats AS (
29    SELECT
30        DATE_FORMAT(created_at, '%Y-%m') AS month,
31        COUNT(*) AS post_count,
32        SUM(view_count) AS total_views,
33        AVG(view_count) AS avg_views,
34        RANK() OVER (ORDER BY COUNT(*) DESC) AS rank
35    FROM articles
36    WHERE is_published = 1
37      AND created_at >= DATE_SUB(NOW(), INTERVAL 12 MONTH)
38    GROUP BY DATE_FORMAT(created_at, '%Y-%m')
39)
40SELECT * FROM monthly_stats
41WHERE rank <= 3
42ORDER BY month DESC;
43
44-- 存储过程
45DELIMITER //
46CREATE PROCEDURE GetPopularPosts(IN limit_count INT)
47BEGIN
48    SELECT
49        a.id, a.title, a.category,
50        a.view_count,
51        JSON_EXTRACT(a.tags, '$[0]') AS primary_tag
52    FROM articles a
53    WHERE a.is_published = 1
54    ORDER BY a.view_count DESC
55    LIMIT limit_count;
56END //
57DELIMITER ;
58
59CALL GetPopularPosts(10);

8. TypeScript

 1/**
 2 * TypeScript 类型安全代码示例
 3 */
 4
 5// 接口与泛型
 6interface Article<T extends object = Record<string, unknown>> {
 7  id: number;
 8  title: string;
 9  content: string;
10  meta?: T;
11  createdAt: Date | null;
12}
13
14type ArticleStatus = 'draft' | 'review' | 'published' | 'archived';
15type TagMap = Map<string, Article[]>;
16
17// 泛型工具类型
18type RequiredFields<T, K extends keyof T> = T & Required<Pick<T, K>>;
19type ReadonlyArticle = Readonly<Article>;
20type PartialUpdate = Partial<Pick<Article, 'title' | 'content' | 'meta'>>;
21
22// 装饰器与元数据
23function log(target: unknown, key: string, descriptor: PropertyDescriptor) {
24  const original = descriptor.value;
25  descriptor.value = function (...args: unknown[]) {
26    console.log(`[Call] ${key}(${args.map(JSON.stringify).join(', ')})`);
27    return original.apply(this, args);
28  };
29  return descriptor;
30}
31
32class ArticleService<T> {
33  #storage: Map<number, Article<T>>;
34  #eventEmitter: EventTarget;
35
36  constructor(private readonly dbName: string) {
37    this.#storage = new Map();
38    this.#eventEmitter = new EventTarget();
39  }
40
41  @log
42  async create(data: Omit<Article<T>, 'id' | 'createdAt'>): Promise<Article<T>> {
43    const article: Article<T> = {
44      ...data as unknown as Article<T>,
45      id: crypto.randomUUID(),
46      createdAt: new Date(),
47    };
48    this.#storage.set(article.id, article);
49
50    this.#eventEmitter.dispatchEvent(new CustomEvent('article:created', { detail: article }));
51    return article;
52  }
53
54  // 类型守卫
55  isPublished(article: Article<T> | null): article is RequiredFields<Article<T>, 'createdAt'> {
56    return article !== null && article.createdAt !== null;
57  }
58
59  // 断言函数
60  assertArticle(input: unknown): asserts input is Article<T> {
61    if (!input || typeof input !== 'object' || !('title' in input)) {
62      throw new TypeError('Invalid article shape');
63    }
64  }
65}
66
67// 使用示例
68type TechMeta = { language: string; framework: string };
69
70const service = new ArticleService<TechMeta>('lumin-blog');
71
72await service.create({
73  title: 'TypeScript 高级类型',
74  content: '泛型、条件类型、映射类型...',
75  meta: { language: 'TypeScript', framework: 'Node.js' },
76});

9. YAML

 1# Hugo 配置文件示例
 2baseURL: https://example.com/
 3defaultContentLanguage: zh-cn
 4title: Lumin Blog
 5theme: hugo-theme-lumin
 6
 7server:
 8  address: 127.0.0.1
 9  port: 1313
10
11markup:
12  highlight:
13    codeFences: true
14    guessSyntax: true
15    lineNos: false
16    lineNumbersInTable: false
17    noClasses: false
18    style: monokai
19
20params:
21  author: 博主
22  description: 记录生活,分享技术
23  defaultTheme: light  # light, dark, auto
24
25  footer:
26    since: 2024
27    icp: "粤ICP备XXXXXXXX号"
28    publicSecurity: "粤公网安备 XXXXXXXXX号"
29
30  comments:
31    enable: true
32    type: twikoo
33    twikoo:
34      envId: https://twikoo.example.com
35
36  analytics:
37    enable: true
38    google:
39      id: G-XXXXXXXXXX
40    baidu:
41      id: "1234567890"
42
43menu:
44  - identifier: home
45    name: 首页
46    url: /
47    weight: 10
48  - identifier: about
49    name: 关于
50    url: /about/
51    weight: 70

10. Dockerfile

 1# 多阶段构建示例
 2FROM node:20-alpine AS builder
 3
 4WORKDIR /app
 5
 6# 复制依赖定义文件
 7COPY package.json package-lock.json ./
 8
 9# 安装生产依赖
10RUN npm ci --only=production && npm cache clean --force
11
12# 复制源码并构建
13COPY . .
14RUN npm run build
15
16# 生产镜像
17FROM nginx:alpine
18
19LABEL maintainer="Lumin Blog" \
20      version="1.0.0" \
21      description="Hugo 静态站点"
22
23# 从构建阶段复制产物
24COPY --from=builder /app/public /usr/share/nginx/html
25
26# 复制 nginx 配置
27COPY nginx.conf /etc/nginx/conf.d/default.conf
28
29# 健康检查
30HEALTHCHECK --interval=30s --timeout=3s \
31  CMD wget --no-verbose --tries=1 --spider http://localhost/ || exit 1
32
33# 创建非 root 用户
34RUN addgroup -S nginx && adduser -S -G nginx nginx \
35    && chown -R nginx:nginx /usr/share/nginx/html
36
37USER nginx
38
39EXPOSE 80
40
41CMD ["nginx", "-g", "daemon off;"]

11. JSON

 1{
 2  "$schema": "https://json-schema.org/draft/2020-12/schema",
 3  "title": "Article Schema",
 4  "description": "博客文章数据结构定义",
 5  "type": "object",
 6  "required": ["title", "content", "category"],
 7  "properties": {
 8    "id": {
 9      "type": "string",
10      "format": "uuid",
11      "description": "唯一标识符"
12    },
13    "title": {
14      "type": "string",
15      "minLength": 1,
16      "maxLength": 255
17    },
18    "content": {
19      "type": "string",
20      "description": "Markdown 格式内容"
21    },
22    "category": {
23      "type": "string",
24      "enum": ["life", "tech", "smart", "game", "share"]
25    },
26    "tags": {
27      "type": "array",
28      "items": { "type": "string" },
29      "maxItems": 10
30    },
31    "metadata": {
32      "type": "object",
33      "properties": {
34        "wordCount": { "type": "integer", "minimum": 0 },
35        "readingTime": { "type": "number" },
36        "featuredImage": { "type": ["string", "null"] }
37      }
38    },
39    "createdAt": {
40      "type": "string",
41      "format": "date-time"
42    },
43    "status": {
44      "type": "string",
45      "enum": ["draft", "published", "archived"],
46      "default": "draft"
47    }
48  }
49}

12. Rust

  1//! Rust 代码高亮测试
  2
  3use std::collections::{HashMap, HashSet};
  4use std::sync::Arc;
  5use tokio::sync::RwLock;
  6
  7/// 文章结构体
  8#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
  9pub struct Article {
 10    pub id: uuid::Uuid,
 11    pub title: String,
 12    pub content: String,
 13    #[serde(default)]
 14    pub tags: Vec<String>,
 15    pub created_at: chrono::DateTime<chrono::Utc>,
 16    pub published: bool,
 17}
 18
 19impl Article {
 20    /// 创建新文章
 21    pub fn new(title: impl Into<String>, content: impl Into<String>) -> Self {
 22        Self {
 23            id: uuid::Uuid::new_v4(),
 24            title: title.into(),
 25            content: content.into(),
 26            tags: Vec::new(),
 27            created_at: chrono::Utc::now(),
 28            published: false,
 29        }
 30    }
 31
 32    /// 计算阅读时间估算
 33    pub fn reading_time(&self) -> u32 {
 34        let word_count = self.content.split_whitespace().count();
 35        ((word_count / 200) as u32).max(1)
 36    }
 37}
 38
 39/// 泛型博客引擎
 40pub struct BlogEngine<T: storage::StorageBackend> {
 41    name: String,
 42    storage: Arc<RwLock<T>>,
 43    cache: HashMap<uuid::Uuid, Arc<Article>>,
 44}
 45
 46impl<T: storage::StorageBackend> BlogEngine<T> {
 47    pub async fn create_article(
 48        &mut self,
 49        title: &str,
 50        content: &str,
 51    ) -> Result<Arc<Article>, Box<dyn std::error::Error>> {
 52        let article = Arc::new(Article::new(title, content));
 53        
 54        // 写入存储
 55        {
 56            let mut store = self.storage.write().await;
 57            store.save(&article).await?;
 58        }
 59
 60        // 更新缓存
 61        self.cache.insert(article.id, Arc::clone(&article));
 62
 63        println!("✅ 文章创建成功: {}", article.title);
 64        Ok(article)
 65    }
 66
 67    /// 按标签筛选文章
 68    pub fn filter_by_tag<'a>(&'a self, tag: &str) -> impl Iterator<Item = &'a Arc<Article>> {
 69        self.cache.values().filter(move |a| a.tags.contains(&tag.to_string()))
 70    }
 71
 72    // 模式匹配与错误处理
 73    pub async fn get_or_create(&mut self, id: uuid::Uuid) -> Result<Arc<Article>, Error> {
 74        match self.cache.get(&id) {
 75            Some(article) => Ok(Arc::clone(article)),
 76            None => {
 77                let mut store = self.storage.write().await;
 78                store.load(id).await.ok_or(Error::NotFound(id))
 79            }
 80        }
 81    }
 82}
 83
 84#[derive(thiserror::Error, Debug)]
 85pub enum Error {
 86    #[error("文章不存在: {0}")]
 87    NotFound(uuid::Uuid),
 88    #[error("存储层错误: {0}")]
 89    Storage(String),
 90}
 91
 92#[tokio::main]
 93async fn main() -> Result<(), Box<dyn std::error::Error>> {
 94    let engine = BlogEngine::new("Lumin Blog");
 95    
 96    let article = engine.create_article(
 97        "Rust 入门教程",
 98        "所有权、生命周期、并发模型...",
 99    ).await?;
100    
101    println!("标题: {}, 预计阅读: {} 分钟", 
102             article.title, article.reading_time());
103    
104    Ok(())
105}

说明: 以上共包含 12 种语言/格式的代码块: Bash、HTML、CSS、JavaScript、Python、Go、SQL、TypeScript、YAML、Dockerfile、JSON、Rust。

如果某种语言的颜色不对或没有高亮,可能需要调整 Chroma 配置。

版权声明

本文作者 Lumin

本文链接 https://www.zhengquan.xyz/tech/code-highlight-test/

许可协议 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!

请作者喝杯咖啡 ☕

  • 微信打赏
    微信支付
  • 支付宝打赏
    支付宝
点击按钮查看打赏二维码
🎁 推荐工具
试试这些实用在线工具,提升工作效率
前往工具集 →

留言评论

期待你的想法

评论加载中