语法高亮测试

目录

简介

这篇文章测试我们博客中各种编程语言的语法高亮功能。

Emacs Lisp

;; 定义一个向用户问候的函数
(defun greet-user (name)
  "向 NAME 用户问候。"
  (interactive "s请输入你的名字: ")
  (message "你好,%s!欢迎使用 Emacs。" name))

;; 配置示例
(setq user-full-name "张三"
      user-mail-address "zhangsan@example.com")

;; 使用 let 绑定
(let ((x 10)
      (y 20))
  (+ x y)) ; 返回 30

Python

# Python 类和函数示例
import os
import sys
from datetime import datetime

class BlogPost:
    """一个简单的博客文章类。"""

    def __init__(self, title, content, author="匿名"):
        self.title = title
        self.content = content
        self.author = author
        self.created_at = datetime.now()
        self.tags = []

    def add_tag(self, tag):
        """为文章添加标签。"""
        if tag not in self.tags:
            self.tags.append(tag)

    def __str__(self):
        return f"{self.title} 作者:{self.author}"

# 创建新文章
post = BlogPost("你好世界", "这是我的第一篇文章!")
post.add_tag("python")
post.add_tag("教程")

# 列表推导式示例
numbers = [1, 2, 3, 4, 5]
squares = [n**2 for n in numbers if n % 2 == 0]
print(f"偶数的平方:{squares}")

JavaScript

// 使用 ES6+ 特性的现代 JavaScript
const BlogManager = {
  posts: [],

  // 箭头函数方法
  addPost: (title, content) => {
    const post = {
      id: Date.now(),
      title,
      content,
      createdAt: new Date(),
      tags: new Set()
    };
    BlogManager.posts.push(post);
    return post;
  },

  // 异步函数示例
  async fetchPosts(url) {
    try {
      const response = await fetch(url);
      const data = await response.json();
      return data.posts;
    } catch (error) {
      console.error('获取文章失败:', error);
      return [];
    }
  }
};

// 解构和模板字面量
const { posts } = BlogManager;
const message = `文章总数:${posts.length}`;

// 类示例
class Post {
  constructor(title, content) {
    this.title = title;
    this.content = content;
  }

  get summary() {
    return this.content.substring(0, 100) + '...';
  }
}

Go

package main

import (
    "fmt"
    "time"
)

// BlogPost 表示一篇博客文章
type BlogPost struct {
    ID        int       `json:"id"`
    Title     string    `json:"title"`
    Content   string    `json:"content"`
    Author    string    `json:"author"`
    CreatedAt time.Time `json:"created_at"`
    Tags      []string  `json:"tags"`
}

// NewBlogPost 创建新的博客文章
func NewBlogPost(title, content, author string) *BlogPost {
    return &BlogPost{
        ID:        generateID(),
        Title:     title,
        Content:   content,
        Author:    author,
        CreatedAt: time.Now(),
        Tags:      make([]string, 0),
    }
}

// AddTag 为文章添加标签
func (p *BlogPost) AddTag(tag string) {
    p.Tags = append(p.Tags, tag)
}

func main() {
    // 创建新文章
    post := NewBlogPost("Go 教程", "学习 Go 很有趣!", "Gopher")
    post.AddTag("golang")
    post.AddTag("教程")

    // 使用 defer
    defer fmt.Println("清理完成")

    // Goroutine 示例
    go func() {
        fmt.Println("来自 goroutine 的问候!")
    }()

    // Channel 示例
    ch := make(chan string, 1)
    ch <- "你好,channels!"
    msg := <-ch
    fmt.Println(msg)
}

func generateID() int {
    return int(time.Now().Unix())
}

Rust

use std::collections::HashMap;
use std::fmt;

// 定义博客文章结构体
#[derive(Debug, Clone)]
pub struct BlogPost {
    id: u64,
    title: String,
    content: String,
    author: String,
    tags: Vec<String>,
}

impl BlogPost {
    // 构造方法
    pub fn new(title: String, content: String, author: String) -> Self {
        Self {
            id: generate_id(),
            title,
            content,
            author,
            tags: Vec::new(),
        }
    }

    // 添加标签
    pub fn add_tag(&mut self, tag: String) {
        if !self.tags.contains(&tag) {
            self.tags.push(tag);
        }
    }

    // 获取文章摘要
    pub fn summary(&self) -> String {
        let max_chars = 100;
        if self.content.chars().count() > max_chars {
            let prefix: String = self.content.chars().take(max_chars).collect();
            format!("{}...", prefix)
        } else {
            self.content.clone()
        }
    }
}

// 实现 Display trait
impl fmt::Display for BlogPost {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} 作者:{}", self.title, self.author)
    }
}

fn main() {
    // 创建新文章
    let mut post = BlogPost::new(
        "Rust 教程".to_string(),
        "学习 Rust 令人兴奋!".to_string(),
        "Rustacean".to_string(),
    );

    // 添加标签
    post.add_tag("rust".to_string());
    post.add_tag("系统编程".to_string());

    // 模式匹配
    match post.tags.len() {
        0 => println!("没有标签"),
        1 => println!("一个标签"),
        n => println!("{} 个标签", n),
    }

    // 使用 Option 和 Result
    let maybe_number: Option<i32> = Some(42);
    if let Some(n) = maybe_number {
        println!("答案是 {}", n);
    }

    // 向量和迭代器示例
    let numbers: Vec<i32> = (1..=5).collect();
    let squares: Vec<i32> = numbers.iter().map(|n| n * n).collect();
    println!("平方数:{:?}", squares);
}

fn generate_id() -> u64 {
    use std::time::{SystemTime, UNIX_EPOCH};
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs()
}

Shell 脚本

#!/bin/bash

# 博客发布脚本
BLOG_DIR="$HOME/blog"
POSTS_DIR="$BLOG_DIR/posts"
PUBLIC_DIR="$BLOG_DIR/public"

# 输出颜色
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m' # 无颜色

# 记录日志的函数
log() {
    echo -e "${BLUE}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $1"
}

# 构建博客的函数
build_blog() {
    log "正在构建博客..."

    # 检查目录是否存在
    if [ ! -d "$POSTS_DIR" ]; then
        echo -e "${RED}错误:文章目录未找到!${NC}"
        exit 1
    fi

    # 如果不存在则创建公共目录
    mkdir -p "$PUBLIC_DIR"

    # 使用 Emacs 构建
    emacs --batch \
          --load ~/.config/doom/config.el \
          --eval "(org-publish \"blog\" t)" \
          2>&1 | tee build.log

    # 检查构建是否成功
    if [ ${PIPESTATUS[0]} -eq 0 ]; then
        echo -e "${GREEN}✓ 构建成功!${NC}"
        return 0
    else
        echo -e "${RED}✗ 构建失败!${NC}"
        return 1
    fi
}

# 主执行函数
main() {
    log "开始博客构建过程..."

    if build_blog; then
        log "博客已发布到 $PUBLIC_DIR"

        # 统计文章数量
        post_count=$(find "$POSTS_DIR" -name "*.org" | wc -l)
        log "文章总数:$post_count"
    else
        log "构建失败。请查看 build.log 了解详情。"
        exit 1
    fi
}

# 运行主函数
main "$@"

HTML/CSS

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的博客</title>
    <style>
        /* CSS 样式示例 */
        :root {
            --primary-color: #D4A27F;
            --text-color: #333;
            --bg-color: #FDFDF7;
        }

        body {
            font-family: 'Inter', sans-serif;
            color: var(--text-color);
            background-color: var(--bg-color);
            line-height: 1.6;
        }

        .blog-post {
            max-width: 800px;
            margin: 0 auto;
            padding: 2rem;
        }

        .blog-post h1 {
            color: var(--primary-color);
            font-size: 2.5rem;
            margin-bottom: 1rem;
        }

        @media (max-width: 768px) {
            .blog-post {
                padding: 1rem;
            }
        }
    </style>
</head>
<body>
    <article class="blog-post">
        <h1>欢迎来到我的博客</h1>
        <p>这是一篇带有语法高亮的示例博客文章。</p>
    </article>
</body>
</html>

JSON

{
  "blog": {
    "title": "我的技术博客",
    "author": "bytenoob",
    "description": "关于编程和技术的博客",
    "posts": [
      {
        "id": 1,
        "title": "Emacs 入门指南",
        "date": "2024-01-29",
        "tags": ["emacs", "编辑器", "生产力"],
        "published": true,
        "metadata": {
          "readTime": "10 分钟",
          "views": 1523,
          "likes": 42
        }
      },
      {
        "id": 2,
        "title": "Waku 网络",
        "date": "2024-06-16",
        "tags": ["网络", "p2p", "隐私"],
        "published": true
      }
    ],
    "settings": {
      "theme": "light",
      "commentsEnabled": true,
      "analyticsId": "UA-123456789"
    }
  }
}

YAML

# 博客配置
blog:
  title: 我的技术博客
  author: bytenoob
  email: blog@example.com

  # 主题设置
  theme:
    name: minimal
    colors:
      primary: "#D4A27F"
      secondary: "#333333"
      background: "#FDFDF7"

  # 功能开关
  features:
    comments: true
    search: true
    rss: true
    sitemap: true

  # 分类
  categories:
    - name: 编程
      slug: programming
      description: 关于编程语言和技术的文章
    - name: 运维
      slug: devops
      description: 关于开发运维的文章

  # 社交链接
  social:
    github: https://github.com/bytenoob
    twitter: https://twitter.com/bytenoob
    linkedin: https://linkedin.com/in/bytenoob

SQL

-- 创建博客数据库架构
CREATE DATABASE IF NOT EXISTS blog_db;
USE blog_db;

-- 用户表
CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- 文章表
CREATE TABLE posts (
    id INT PRIMARY KEY AUTO_INCREMENT,
    author_id INT NOT NULL,
    title VARCHAR(200) NOT NULL,
    slug VARCHAR(200) UNIQUE NOT NULL,
    content TEXT NOT NULL,
    summary VARCHAR(500),
    published BOOLEAN DEFAULT FALSE,
    published_at TIMESTAMP NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (author_id) REFERENCES users(id),
    INDEX idx_published (published, published_at),
    FULLTEXT(title, content)
);

-- 标签表
CREATE TABLE tags (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(50) UNIQUE NOT NULL,
    slug VARCHAR(50) UNIQUE NOT NULL
);

-- 文章标签关联表
CREATE TABLE post_tags (
    post_id INT NOT NULL,
    tag_id INT NOT NULL,
    PRIMARY KEY (post_id, tag_id),
    FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE,
    FOREIGN KEY (tag_id) REFERENCES tags(id) ON DELETE CASCADE
);

-- 示例查询:获取最近的文章及标签
SELECT 
    p.id,
    p.title,
    p.summary,
    p.published_at,
    u.username AS author,
    GROUP_CONCAT(t.name) AS tags
FROM posts p
JOIN users u ON p.author_id = u.id
LEFT JOIN post_tags pt ON p.id = pt.post_id
LEFT JOIN tags t ON pt.tag_id = t.id
WHERE p.published = TRUE
GROUP BY p.id
ORDER BY p.published_at DESC
LIMIT 10;

结语

这篇文章演示了各种编程语言的语法高亮。高亮质量取决于:

  1. 是否有 htmlize.el 可用
  2. Emacs 中是否安装了特定语言模式
  3. 为语法高亮定义的 CSS 类

具有 Emacs 内置支持的语言(如 Emacs Lisp、Python、JavaScript)应该高亮良好。其他语言可能显示基本或无高亮,具体取决于你的 Emacs 配置。