✨ added support for language, topic, and preset acquisition and detection functions
This commit is contained in:
78
README.md
78
README.md
@@ -8,15 +8,16 @@ FreezeLib is a Go library for generating beautiful screenshots of code and termi
|
||||
|
||||
## Features
|
||||
|
||||
- 🎨 **Syntax Highlighting**: Support for 100+ programming languages
|
||||
- 🎨 **Syntax Highlighting**: Support for 270+ programming languages
|
||||
- 🔍 **Auto Language Detection**: Intelligent language detection from code content and filenames
|
||||
- 📋 **Simple Lists**: Easy access to all available languages, themes, and presets
|
||||
- 🖼️ **Multiple Output Formats**: Generate SVG and PNG images
|
||||
- 🎭 **Rich Themes**: Built-in themes including GitHub, Dracula, Monokai, and more
|
||||
- 🎭 **Rich Themes**: 67+ built-in themes including GitHub, Dracula, Monokai, and more
|
||||
- 🪟 **Window Controls**: macOS-style window decorations
|
||||
- 📏 **Line Numbers**: Optional line numbering
|
||||
- 🌈 **ANSI Support**: Render colored terminal output
|
||||
- ⚡ **Easy API**: Simple and chainable API design
|
||||
- 🎯 **Presets**: Pre-configured styles for common use cases
|
||||
- 🎯 **Presets**: 10 pre-configured styles for common use cases
|
||||
- 🔧 **Highly Customizable**: Fine-tune every aspect of the output
|
||||
|
||||
## Installation
|
||||
@@ -217,6 +218,29 @@ detector := freeze.GetLanguageDetector()
|
||||
detector.AddCustomMapping(".myext", "python")
|
||||
```
|
||||
|
||||
### Available Options
|
||||
|
||||
Get lists of all available options:
|
||||
|
||||
```go
|
||||
freeze := freezelib.New()
|
||||
|
||||
// Get all available options (sorted lists)
|
||||
languages := freeze.GetSupportedLanguages() // 270+ languages
|
||||
themes := freeze.GetSupportedThemes() // 67+ themes
|
||||
presets := freeze.GetAvailablePresets() // 10 presets
|
||||
|
||||
// Test support
|
||||
isSupported := freeze.IsLanguageSupported("go")
|
||||
isSupported = freeze.IsThemeSupported("github")
|
||||
isValid := freezelib.IsValidPreset("dark")
|
||||
|
||||
// Global functions also available
|
||||
languages = freezelib.GetSupportedLanguages()
|
||||
themes = freezelib.GetSupportedThemes()
|
||||
presets = freezelib.GetAvailablePresets()
|
||||
```
|
||||
|
||||
### Chainable Methods
|
||||
|
||||
Both `Freeze` and `QuickFreeze` support method chaining:
|
||||
@@ -282,27 +306,41 @@ for _, file := range files {
|
||||
|
||||
## Supported Languages
|
||||
|
||||
FreezeLib supports syntax highlighting for 100+ programming languages including:
|
||||
FreezeLib supports syntax highlighting for 270+ programming languages including:
|
||||
|
||||
- Go, Rust, Python, JavaScript, TypeScript
|
||||
- C, C++, C#, Java, Kotlin, Swift
|
||||
- HTML, CSS, SCSS, JSON, YAML, XML
|
||||
- Shell, PowerShell, Dockerfile
|
||||
- SQL, GraphQL, Markdown
|
||||
- And many more...
|
||||
### Popular Languages
|
||||
- **System**: Go, Rust, C, C++, Zig, D, Nim, V
|
||||
- **Web**: JavaScript, TypeScript, HTML, CSS, SCSS, PHP
|
||||
- **Enterprise**: Java, C#, Kotlin, Scala, Swift
|
||||
- **Scripting**: Python, Ruby, Perl, Lua, Bash, PowerShell
|
||||
- **Data**: JSON, YAML, TOML, XML, SQL, GraphQL
|
||||
|
||||
### Categories
|
||||
- **Popular** (30): Most commonly used languages
|
||||
- **Web** (15): Frontend and backend web technologies
|
||||
- **System** (13): Low-level and systems programming
|
||||
- **Scripting** (12): Automation and scripting languages
|
||||
- **Data** (11): Configuration and data formats
|
||||
- **And many more**: 270+ total languages supported
|
||||
|
||||
## Supported Themes
|
||||
|
||||
Popular themes include:
|
||||
- `github` / `github-dark`
|
||||
- `dracula`
|
||||
- `monokai`
|
||||
- `solarized-dark` / `solarized-light`
|
||||
- `nord`
|
||||
- `one-dark`
|
||||
- `material`
|
||||
- `vim`
|
||||
- And many more...
|
||||
FreezeLib includes 67+ syntax highlighting themes:
|
||||
|
||||
### Popular Themes
|
||||
- **GitHub**: `github`, `github-dark`
|
||||
- **Modern**: `dracula`, `monokai`, `nord`, `one-dark`
|
||||
- **Classic**: `solarized-dark`, `solarized-light`, `material`, `vim`
|
||||
- **Colorful**: `colorful`, `friendly`, `fruity`, `rainbow_dash`
|
||||
|
||||
### Categories
|
||||
- **Popular** (30): Most commonly used themes
|
||||
- **Dark** (10): Dark color schemes for low-light environments
|
||||
- **Light** (14): Light color schemes for bright environments
|
||||
- **And many more**: 67+ total themes available
|
||||
|
||||
### Simple and Efficient
|
||||
All lists are sorted alphabetically for easy browsing and selection.
|
||||
|
||||
## Error Handling
|
||||
|
||||
|
210
README_CN.md
210
README_CN.md
@@ -8,14 +8,16 @@ FreezeLib 是一个用于生成美观代码和终端输出截图的 Go 库。它
|
||||
|
||||
## 特性
|
||||
|
||||
- 🎨 **语法高亮**: 支持 100+ 种编程语言
|
||||
- 🎨 **语法高亮**: 支持 270+ 种编程语言
|
||||
- 🔍 **自动语言检测**: 智能检测代码内容和文件名的语言
|
||||
- 📋 **简单列表**: 轻松访问所有可用的语言、主题和预设
|
||||
- 🖼️ **多种输出格式**: 生成 SVG 和 PNG 图像
|
||||
- 🎭 **丰富主题**: 内置主题包括 GitHub、Dracula、Monokai 等
|
||||
- 🎭 **丰富主题**: 67+ 内置主题,包括 GitHub、Dracula、Monokai 等
|
||||
- 🪟 **窗口控件**: macOS 风格的窗口装饰
|
||||
- 📏 **行号**: 可选的行号显示
|
||||
- 🌈 **ANSI 支持**: 渲染彩色终端输出
|
||||
- ⚡ **简易 API**: 简单且可链式调用的 API 设计
|
||||
- 🎯 **预设配置**: 常见用例的预配置样式
|
||||
- 🎯 **预设配置**: 10 种预配置样式,适用于常见用例
|
||||
- 🔧 **高度可定制**: 精细调整输出的每个方面
|
||||
|
||||
## 安装
|
||||
@@ -60,6 +62,50 @@ func main() {
|
||||
}
|
||||
```
|
||||
|
||||
### 自动语言检测
|
||||
|
||||
FreezeLib 可以自动检测编程语言:
|
||||
|
||||
```go
|
||||
freeze := freezelib.New()
|
||||
|
||||
// 从代码内容自动检测语言
|
||||
svgData, err := freeze.GenerateFromCodeAuto(code)
|
||||
|
||||
// 手动检测语言
|
||||
language := freeze.DetectLanguage(code)
|
||||
fmt.Printf("检测到的语言: %s", language)
|
||||
|
||||
// 从文件名检测语言
|
||||
language = freeze.DetectLanguageFromFilename("script.py")
|
||||
|
||||
// 组合检测(文件名 + 内容)
|
||||
language = freeze.DetectLanguageFromFile("script.py", code)
|
||||
```
|
||||
|
||||
### 可用选项
|
||||
|
||||
获取所有可用选项的列表:
|
||||
|
||||
```go
|
||||
freeze := freezelib.New()
|
||||
|
||||
// 获取所有可用选项(排序列表)
|
||||
languages := freeze.GetSupportedLanguages() // 270+ 种语言
|
||||
themes := freeze.GetSupportedThemes() // 67+ 种主题
|
||||
presets := freeze.GetAvailablePresets() // 10 种预设
|
||||
|
||||
// 测试支持
|
||||
isSupported := freeze.IsLanguageSupported("go")
|
||||
isSupported = freeze.IsThemeSupported("github")
|
||||
isValid := freezelib.IsValidPreset("dark")
|
||||
|
||||
// 全局函数也可用
|
||||
languages = freezelib.GetSupportedLanguages()
|
||||
themes = freezelib.GetSupportedThemes()
|
||||
presets = freezelib.GetAvailablePresets()
|
||||
```
|
||||
|
||||
### QuickFreeze API
|
||||
|
||||
为了更流畅的体验,使用 QuickFreeze API:
|
||||
@@ -72,7 +118,7 @@ svgData, err := qf.WithTheme("dracula").
|
||||
WithWindow().
|
||||
WithShadow().
|
||||
WithLineNumbers().
|
||||
CodeToSVG(code)
|
||||
CodeToSVGAuto(code) // 自动检测语言
|
||||
```
|
||||
|
||||
## API 参考
|
||||
@@ -104,6 +150,10 @@ qf := freezelib.NewQuickFreezeWithPreset("terminal")
|
||||
```go
|
||||
svgData, err := freeze.GenerateFromCode(code, "python")
|
||||
pngData, err := freeze.GeneratePNGFromCode(code, "python")
|
||||
|
||||
// 使用自动语言检测
|
||||
svgData, err := freeze.GenerateFromCodeAuto(code)
|
||||
pngData, err := freeze.GeneratePNGFromCodeAuto(code)
|
||||
```
|
||||
|
||||
#### 从文件
|
||||
@@ -153,18 +203,18 @@ config.SetLines(10, 20) // 行范围(1-indexed)
|
||||
FreezeLib 提供了几个内置预设:
|
||||
|
||||
```go
|
||||
// 可用预设
|
||||
// 可用预设(10 种)
|
||||
presets := []string{
|
||||
"base", // 简洁干净
|
||||
"full", // macOS 风格窗口控件
|
||||
"terminal", // 终端输出优化
|
||||
"presentation", // 演示高对比度
|
||||
"minimal", // 极简样式
|
||||
"base", // 基础配置
|
||||
"full", // 完整功能配置
|
||||
"terminal", // 终端风格
|
||||
"dark", // 深色主题
|
||||
"light", // 浅色主题
|
||||
"retro", // 复古终端风格
|
||||
"neon", // 霓虹/赛博朋克风格
|
||||
"compact", // 小代码片段紧凑型
|
||||
"minimal", // 极简风格
|
||||
"professional", // 专业风格
|
||||
"vibrant", // 鲜艳配色
|
||||
"retro", // 复古风格
|
||||
"neon", // 霓虹风格
|
||||
}
|
||||
|
||||
freeze := freezelib.NewWithPreset("dark")
|
||||
@@ -187,6 +237,18 @@ svgData, err := freeze.GenerateFromCode(code, "rust")
|
||||
|
||||
## 示例
|
||||
|
||||
查看 `examples/` 目录获取完整示例:
|
||||
|
||||
- `01-basic/` - 基础用法示例
|
||||
- `02-formats/` - 输出格式示例
|
||||
- `03-themes/` - 主题展示
|
||||
- `04-languages/` - 语言支持示例
|
||||
- `05-terminal/` - 终端输出示例
|
||||
- `06-advanced/` - 高级配置
|
||||
- `07-batch/` - 批量处理
|
||||
- `08-auto-language-detection/` - 自动语言检测
|
||||
- `09-supported-options/` - 支持选项列表
|
||||
|
||||
### 终端输出截图
|
||||
|
||||
```go
|
||||
@@ -235,27 +297,115 @@ for _, file := range files {
|
||||
|
||||
## 支持的语言
|
||||
|
||||
FreezeLib 支持 100+ 种编程语言的语法高亮,包括:
|
||||
FreezeLib 支持 270+ 种编程语言的语法高亮:
|
||||
|
||||
- Go, Rust, Python, JavaScript, TypeScript
|
||||
- C, C++, C#, Java, Kotlin, Swift
|
||||
- HTML, CSS, SCSS, JSON, YAML, XML
|
||||
- Shell, PowerShell, Dockerfile
|
||||
- SQL, GraphQL, Markdown
|
||||
- 等等...
|
||||
### 热门语言
|
||||
- **系统级**: Go, Rust, C, C++, Zig, D, Nim, V
|
||||
- **Web**: JavaScript, TypeScript, HTML, CSS, SCSS, PHP
|
||||
- **企业级**: Java, C#, Kotlin, Scala, Swift
|
||||
- **脚本**: Python, Ruby, Perl, Lua, Bash, PowerShell
|
||||
- **数据**: JSON, YAML, TOML, XML, SQL, GraphQL
|
||||
|
||||
### 分类
|
||||
- **热门** (30): 最常用的语言
|
||||
- **Web** (15): 前端和后端 Web 技术
|
||||
- **系统** (13): 底层和系统编程
|
||||
- **脚本** (12): 自动化和脚本语言
|
||||
- **数据** (11): 配置和数据格式
|
||||
- **更多**: 总共支持 270+ 种语言
|
||||
|
||||
## 支持的主题
|
||||
|
||||
流行主题包括:
|
||||
- `github` / `github-dark`
|
||||
- `dracula`
|
||||
- `monokai`
|
||||
- `solarized-dark` / `solarized-light`
|
||||
- `nord`
|
||||
- `one-dark`
|
||||
- `material`
|
||||
- `vim`
|
||||
- 等等...
|
||||
FreezeLib 包含 67+ 种语法高亮主题:
|
||||
|
||||
### 热门主题
|
||||
- **GitHub**: `github`, `github-dark`
|
||||
- **现代**: `dracula`, `monokai`, `nord`, `one-dark`
|
||||
- **经典**: `solarized-dark`, `solarized-light`, `material`, `vim`
|
||||
- **多彩**: `colorful`, `friendly`, `fruity`, `rainbow_dash`
|
||||
|
||||
### 分类
|
||||
- **热门** (30): 最常用的主题
|
||||
- **深色** (10): 适合低光环境的深色配色方案
|
||||
- **浅色** (14): 适合明亮环境的浅色配色方案
|
||||
- **更多**: 总共 67+ 种主题可用
|
||||
|
||||
### 简单高效
|
||||
所有列表都按字母顺序排序,便于浏览和选择。
|
||||
|
||||
## 语言检测功能
|
||||
|
||||
### 自动检测方法
|
||||
```go
|
||||
freeze := freezelib.New()
|
||||
|
||||
// 从代码内容检测语言
|
||||
language := freeze.DetectLanguage(code)
|
||||
|
||||
// 从文件名检测
|
||||
language = freeze.DetectLanguageFromFilename("script.py")
|
||||
|
||||
// 组合检测(文件名 + 内容)
|
||||
language = freeze.DetectLanguageFromFile("script.py", code)
|
||||
|
||||
// 检查语言支持
|
||||
supported := freeze.IsLanguageSupported("go")
|
||||
|
||||
// 获取所有支持的语言
|
||||
languages := freeze.GetSupportedLanguages()
|
||||
```
|
||||
|
||||
### 自定义语言检测器
|
||||
```go
|
||||
detector := freeze.GetLanguageDetector()
|
||||
|
||||
// 添加自定义文件扩展名映射
|
||||
detector.AddCustomMapping(".myext", "python")
|
||||
detector.AddCustomMapping(".config", "json")
|
||||
|
||||
// 配置检测策略
|
||||
detector.EnableContentAnalysis = true
|
||||
detector.EnableFilenameAnalysis = true
|
||||
detector.FallbackLanguage = "text"
|
||||
```
|
||||
|
||||
## 支持选项
|
||||
|
||||
### 获取所有可用选项
|
||||
```go
|
||||
freeze := freezelib.New()
|
||||
|
||||
// 获取所有可用选项(排序列表)
|
||||
languages := freeze.GetSupportedLanguages() // 270+ 种语言
|
||||
themes := freeze.GetSupportedThemes() // 67+ 种主题
|
||||
presets := freeze.GetAvailablePresets() // 10 种预设
|
||||
|
||||
// 测试支持
|
||||
isSupported := freeze.IsLanguageSupported("go")
|
||||
isSupported = freeze.IsThemeSupported("github")
|
||||
isValid := freezelib.IsValidPreset("dark")
|
||||
|
||||
// 全局函数也可用
|
||||
languages = freezelib.GetSupportedLanguages()
|
||||
themes = freezelib.GetSupportedThemes()
|
||||
presets = freezelib.GetAvailablePresets()
|
||||
```
|
||||
|
||||
### 验证支持
|
||||
```go
|
||||
// 检查支持
|
||||
if freeze.IsLanguageSupported("go") {
|
||||
// 生成 Go 代码截图
|
||||
}
|
||||
|
||||
if freeze.IsThemeSupported("dracula") {
|
||||
// 使用 Dracula 主题
|
||||
}
|
||||
|
||||
if freezelib.IsValidPreset("dark") {
|
||||
// 使用深色预设
|
||||
}
|
||||
```
|
||||
|
||||
## 错误处理
|
||||
|
||||
|
350
USAGE.md
350
USAGE.md
@@ -2,13 +2,17 @@
|
||||
|
||||
**Language / 语言**: [English](USAGE_EN.md) | [中文](USAGE.md)
|
||||
|
||||
**Main Documentation / 主要文档**: [README (English)](README.md) | [README (中文)](README_CN.md)
|
||||
FreezeLib 是一个 Go 库,用于生成美观的代码截图。
|
||||
|
||||
FreezeLib 是一个基于 Charm 的 freeze CLI 工具重构的 Go 公共库,用于生成美观的代码截图。
|
||||
## 安装
|
||||
|
||||
## 🚀 快速开始
|
||||
```bash
|
||||
go get github.com/landaiqing/freezelib
|
||||
```
|
||||
|
||||
### 基本用法
|
||||
## 基本使用
|
||||
|
||||
### 1. 最简单的例子
|
||||
|
||||
```go
|
||||
package main
|
||||
@@ -19,10 +23,10 @@ import (
|
||||
)
|
||||
|
||||
func main() {
|
||||
// 创建 freeze 实例
|
||||
// 创建实例
|
||||
freeze := freezelib.New()
|
||||
|
||||
// 要截图的代码
|
||||
// 代码内容
|
||||
code := `package main
|
||||
|
||||
import "fmt"
|
||||
@@ -37,228 +41,194 @@ func main() {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// 保存到文件
|
||||
// 保存文件
|
||||
os.WriteFile("hello.svg", svgData, 0644)
|
||||
}
|
||||
```
|
||||
|
||||
### 链式调用 API
|
||||
### 2. 从文件生成
|
||||
|
||||
```go
|
||||
// 使用 QuickFreeze 进行链式调用
|
||||
qf := freezelib.NewQuickFreeze()
|
||||
|
||||
svgData, err := qf.WithTheme("dracula").
|
||||
WithFont("Fira Code", 14).
|
||||
WithWindow().
|
||||
WithShadow().
|
||||
WithLineNumbers().
|
||||
WithLanguage("javascript").
|
||||
CodeToSVG(code)
|
||||
```
|
||||
|
||||
## 📋 主要功能
|
||||
|
||||
### 1. 多种输入方式
|
||||
|
||||
```go
|
||||
// 从代码字符串生成
|
||||
svgData, err := freeze.GenerateFromCode(code, "python")
|
||||
|
||||
// 从文件生成
|
||||
// 直接从文件生成
|
||||
svgData, err := freeze.GenerateFromFile("main.go")
|
||||
|
||||
// 从 ANSI 终端输出生成
|
||||
ansiOutput := "\033[32m✓ SUCCESS\033[0m: Build completed"
|
||||
svgData, err := freeze.GenerateFromANSI(ansiOutput)
|
||||
|
||||
// 从 Reader 生成
|
||||
svgData, err := freeze.GenerateFromReader(reader, "javascript")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
os.WriteFile("main.svg", svgData, 0644)
|
||||
```
|
||||
|
||||
### 2. 多种输出格式
|
||||
### 3. 生成 PNG 格式
|
||||
|
||||
```go
|
||||
// 生成 SVG
|
||||
svgData, err := freeze.GenerateFromCode(code, "go")
|
||||
|
||||
// 生成 PNG
|
||||
// 生成 PNG 而不是 SVG
|
||||
pngData, err := freeze.GeneratePNGFromCode(code, "go")
|
||||
|
||||
// 直接保存到文件
|
||||
err := freeze.SaveCodeToFile(code, "go", "output.svg")
|
||||
err := freeze.SaveCodeToFile(code, "go", "output.png") // 自动检测格式
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
os.WriteFile("hello.png", pngData, 0644)
|
||||
```
|
||||
|
||||
### 3. 预设配置
|
||||
### 4. 直接保存到文件
|
||||
|
||||
```go
|
||||
// 使用预设配置
|
||||
// 一步完成:生成并保存
|
||||
err := freeze.SaveCodeToFile(code, "go", "output.svg")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// 自动检测格式(根据文件扩展名)
|
||||
err = freeze.SaveCodeToFile(code, "go", "output.png")
|
||||
```
|
||||
|
||||
## 使用预设样式
|
||||
|
||||
```go
|
||||
// 使用预设配置,快速开始
|
||||
freeze := freezelib.NewWithPreset("dark") // 深色主题
|
||||
freeze := freezelib.NewWithPreset("terminal") // 终端风格
|
||||
freeze := freezelib.NewWithPreset("presentation") // 演示风格
|
||||
|
||||
// 可用预设
|
||||
presets := []string{
|
||||
"base", // 基础样式
|
||||
"full", // macOS 风格
|
||||
"terminal", // 终端优化
|
||||
"presentation", // 演示优化
|
||||
"minimal", // 极简风格
|
||||
"dark", // 深色主题
|
||||
"light", // 浅色主题
|
||||
"retro", // 复古风格
|
||||
"neon", // 霓虹风格
|
||||
"compact", // 紧凑风格
|
||||
}
|
||||
// 查看所有可用预设
|
||||
presets := freeze.GetAvailablePresets()
|
||||
// 返回: ["base", "compact", "dark", "full", "light", "minimal", "neon", "presentation", "retro", "terminal"]
|
||||
```
|
||||
|
||||
### 4. 自定义配置
|
||||
## 自定义样式
|
||||
|
||||
```go
|
||||
config := freezelib.DefaultConfig()
|
||||
|
||||
// 基本设置
|
||||
config.SetTheme("github-dark")
|
||||
config.SetFont("JetBrains Mono", 14)
|
||||
config.SetBackground("#1e1e1e")
|
||||
config.SetLanguage("python")
|
||||
|
||||
// 布局设置
|
||||
config.SetPadding(20) // 所有边
|
||||
config.SetPadding(20, 40) // 垂直,水平
|
||||
config.SetPadding(20, 40, 20, 40) // 上,右,下,左
|
||||
config.SetMargin(15)
|
||||
config.SetDimensions(800, 600)
|
||||
|
||||
// 装饰效果
|
||||
config.SetWindow(true) // 窗口控件
|
||||
config.SetLineNumbers(true) // 行号
|
||||
config.SetShadow(20, 0, 10) // 阴影:模糊,X偏移,Y偏移
|
||||
config.SetBorder(1, 8, "#333") // 边框:宽度,圆角,颜色
|
||||
|
||||
// 行范围(1-indexed)
|
||||
config.SetLines(10, 20) // 只截取第10-20行
|
||||
|
||||
freeze := freezelib.NewWithConfig(config)
|
||||
```
|
||||
|
||||
## 🎨 支持的主题
|
||||
|
||||
- `github` / `github-dark`
|
||||
- `dracula`
|
||||
- `monokai`
|
||||
- `solarized-dark` / `solarized-light`
|
||||
- `nord`
|
||||
- `one-dark`
|
||||
- `material`
|
||||
- `vim`
|
||||
- 等等...
|
||||
|
||||
## 💻 支持的语言
|
||||
|
||||
支持 100+ 种编程语言,包括:
|
||||
- Go, Rust, Python, JavaScript, TypeScript
|
||||
- C, C++, C#, Java, Kotlin, Swift
|
||||
- HTML, CSS, SCSS, JSON, YAML, XML
|
||||
- Shell, PowerShell, Dockerfile
|
||||
- SQL, GraphQL, Markdown
|
||||
- 等等...
|
||||
|
||||
## 🔧 高级用法
|
||||
|
||||
### 批量处理
|
||||
|
||||
```go
|
||||
files := []string{"main.go", "config.go", "utils.go"}
|
||||
|
||||
for _, file := range files {
|
||||
svgData, err := freeze.GenerateFromFile(file)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
outputFile := strings.TrimSuffix(file, ".go") + ".svg"
|
||||
os.WriteFile(outputFile, svgData, 0644)
|
||||
}
|
||||
```
|
||||
|
||||
### 终端输出截图
|
||||
|
||||
```go
|
||||
freeze := freezelib.NewWithPreset("terminal")
|
||||
|
||||
ansiOutput := "\033[32m✓ Tests passed\033[0m\n" +
|
||||
"\033[31m✗ Build failed\033[0m\n" +
|
||||
"\033[33m⚠ Warning: deprecated API\033[0m"
|
||||
|
||||
svgData, err := freeze.GenerateFromANSI(ansiOutput)
|
||||
```
|
||||
|
||||
### 链式方法
|
||||
### 基本设置
|
||||
|
||||
```go
|
||||
freeze := freezelib.New().
|
||||
WithTheme("monokai").
|
||||
WithFont("Cascadia Code", 15).
|
||||
WithWindow(true).
|
||||
WithShadow(20, 0, 10).
|
||||
WithLineNumbers(true)
|
||||
WithTheme("github-dark"). // 设置主题
|
||||
WithFont("JetBrains Mono", 14). // 设置字体和大小
|
||||
WithBackground("#1e1e1e"). // 设置背景色
|
||||
WithPadding(20) // 设置内边距
|
||||
|
||||
svgData, err := freeze.GenerateFromCode(code, "rust")
|
||||
svgData, err := freeze.GenerateFromCode(code, "go")
|
||||
```
|
||||
|
||||
## 📊 性能优化建议
|
||||
### 添加装饰效果
|
||||
|
||||
1. **重用实例**:创建一个 `Freeze` 实例并重复使用
|
||||
2. **选择合适格式**:网页用 SVG,演示用 PNG
|
||||
3. **设置具体尺寸**:指定尺寸可提高性能
|
||||
4. **批量操作**:在单个会话中处理多个文件
|
||||
```go
|
||||
freeze := freezelib.New().
|
||||
WithTheme("dracula").
|
||||
WithWindow(true). // 添加窗口控件
|
||||
WithLineNumbers(true). // 显示行号
|
||||
WithShadow(20, 0, 10) // 添加阴影
|
||||
|
||||
## 🐛 错误处理
|
||||
svgData, err := freeze.GenerateFromCode(code, "python")
|
||||
```
|
||||
|
||||
## 查看支持的选项
|
||||
|
||||
```go
|
||||
freeze := freezelib.New()
|
||||
|
||||
// 查看所有支持的语言(270+ 种)
|
||||
languages := freeze.GetSupportedLanguages()
|
||||
fmt.Printf("支持 %d 种语言\n", len(languages))
|
||||
|
||||
// 查看所有支持的主题(67+ 种)
|
||||
themes := freeze.GetSupportedThemes()
|
||||
fmt.Printf("支持 %d 种主题\n", len(themes))
|
||||
|
||||
// 查看所有可用预设(10 种)
|
||||
presets := freeze.GetAvailablePresets()
|
||||
fmt.Printf("可用预设: %v\n", presets)
|
||||
```
|
||||
|
||||
## 终端输出截图
|
||||
|
||||
```go
|
||||
// 截图终端输出(支持 ANSI 颜色)
|
||||
freeze := freezelib.NewWithPreset("terminal")
|
||||
|
||||
ansiOutput := "\033[32m✓ 测试通过\033[0m\n" +
|
||||
"\033[31m✗ 构建失败\033[0m\n" +
|
||||
"\033[33m⚠ 警告: API 已废弃\033[0m"
|
||||
|
||||
svgData, err := freeze.GenerateFromANSI(ansiOutput)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
os.WriteFile("terminal.svg", svgData, 0644)
|
||||
```
|
||||
|
||||
## 批量处理文件
|
||||
|
||||
```go
|
||||
freeze := freezelib.NewWithPreset("dark")
|
||||
files := []string{"main.go", "config.go", "utils.go"}
|
||||
|
||||
for _, file := range files {
|
||||
err := freeze.SaveFileToFile(file, file+".svg")
|
||||
if err != nil {
|
||||
fmt.Printf("处理 %s 失败: %v\n", file, err)
|
||||
continue
|
||||
}
|
||||
fmt.Printf("已生成: %s.svg\n", file)
|
||||
}
|
||||
```
|
||||
|
||||
## 自动语言检测
|
||||
|
||||
```go
|
||||
freeze := freezelib.New()
|
||||
|
||||
// 不指定语言,自动检测
|
||||
code := `function hello() {
|
||||
console.log("Hello, World!");
|
||||
}`
|
||||
|
||||
// 自动检测为 JavaScript
|
||||
svgData, err := freeze.GenerateFromCodeAuto(code)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
os.WriteFile("auto.svg", svgData, 0644)
|
||||
```
|
||||
|
||||
## 错误处理
|
||||
|
||||
```go
|
||||
svgData, err := freeze.GenerateFromCode(code, "go")
|
||||
if err != nil {
|
||||
switch {
|
||||
case strings.Contains(err.Error(), "language"):
|
||||
// 语言检测失败
|
||||
case strings.Contains(err.Error(), "config"):
|
||||
// 配置错误
|
||||
default:
|
||||
// 其他错误
|
||||
}
|
||||
fmt.Printf("生成失败: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
// 保存文件
|
||||
err = os.WriteFile("output.svg", svgData, 0644)
|
||||
if err != nil {
|
||||
fmt.Printf("保存失败: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println("生成成功!")
|
||||
```
|
||||
|
||||
## 📁 项目结构
|
||||
## 常用主题
|
||||
|
||||
```
|
||||
freezelib/
|
||||
├── freeze.go # 主要 API 接口
|
||||
├── config.go # 配置结构体
|
||||
├── generator.go # 核心生成逻辑
|
||||
├── quickfreeze.go # 简化 API
|
||||
├── presets.go # 预设配置
|
||||
├── ansi.go # ANSI 处理
|
||||
├── svg/ # SVG 处理
|
||||
├── font/ # 字体处理
|
||||
├── example/ # 使用示例
|
||||
└── README.md # 详细文档
|
||||
```
|
||||
- `github` - GitHub 浅色主题
|
||||
- `github-dark` - GitHub 深色主题
|
||||
- `dracula` - Dracula 主题
|
||||
- `monokai` - Monokai 主题
|
||||
- `nord` - Nord 主题
|
||||
|
||||
## 🤝 与原版 freeze 的区别
|
||||
## 常用语言
|
||||
|
||||
| 特性 | 原版 freeze | FreezeLib |
|
||||
|------|-------------|-----------|
|
||||
| 使用方式 | CLI 工具 | Go 库 |
|
||||
| 集成方式 | 命令行调用 | 直接导入 |
|
||||
| 配置方式 | 命令行参数/配置文件 | Go 结构体 |
|
||||
| 扩展性 | 有限 | 高度可扩展 |
|
||||
| 性能 | 进程启动开销 | 内存中处理 |
|
||||
|
||||
## 📝 示例代码
|
||||
|
||||
查看 `examples` 目录中的完整示例:
|
||||
|
||||
这将生成多个示例 SVG 文件,展示库的各种功能。
|
||||
- `go` - Go 语言
|
||||
- `python` - Python
|
||||
- `javascript` - JavaScript
|
||||
- `typescript` - TypeScript
|
||||
- `java` - Java
|
||||
- `rust` - Rust
|
||||
- `c` - C 语言
|
||||
- `cpp` - C++
|
||||
- `html` - HTML
|
||||
- `css` - CSS
|
||||
- `json` - JSON
|
||||
- `yaml` - YAML
|
||||
- `markdown` - Markdown
|
||||
- `bash` - Shell 脚本
|
||||
|
312
USAGE_EN.md
312
USAGE_EN.md
@@ -2,13 +2,17 @@
|
||||
|
||||
**Language / 语言**: [English](USAGE_EN.md) | [中文](USAGE.md)
|
||||
|
||||
**Main Documentation / 主要文档**: [README (English)](README.md) | [README (中文)](README_CN.md)
|
||||
FreezeLib is a Go library for generating beautiful code screenshots.
|
||||
|
||||
FreezeLib is a Go library refactored from Charm's freeze CLI tool for generating beautiful code screenshots.
|
||||
## Installation
|
||||
|
||||
## 🚀 Quick Start
|
||||
```bash
|
||||
go get github.com/landaiqing/freezelib
|
||||
```
|
||||
|
||||
### Basic Usage
|
||||
## Basic Usage
|
||||
|
||||
### 1. Simplest Example
|
||||
|
||||
```go
|
||||
package main
|
||||
@@ -19,10 +23,10 @@ import (
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Create freeze instance
|
||||
// Create instance
|
||||
freeze := freezelib.New()
|
||||
|
||||
// Code to screenshot
|
||||
// Code content
|
||||
code := `package main
|
||||
|
||||
import "fmt"
|
||||
@@ -37,155 +41,107 @@ func main() {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Save to file
|
||||
// Save file
|
||||
os.WriteFile("hello.svg", svgData, 0644)
|
||||
}
|
||||
```
|
||||
|
||||
### Chainable API
|
||||
### 2. Generate from File
|
||||
|
||||
```go
|
||||
// Use QuickFreeze for method chaining
|
||||
qf := freezelib.NewQuickFreeze()
|
||||
|
||||
svgData, err := qf.WithTheme("dracula").
|
||||
WithFont("Fira Code", 14).
|
||||
WithWindow().
|
||||
WithShadow().
|
||||
WithLineNumbers().
|
||||
WithLanguage("javascript").
|
||||
CodeToSVG(code)
|
||||
```
|
||||
|
||||
## 📋 Main Features
|
||||
|
||||
### 1. Multiple Input Methods
|
||||
|
||||
```go
|
||||
// Generate from code string
|
||||
svgData, err := freeze.GenerateFromCode(code, "python")
|
||||
|
||||
// Generate from file
|
||||
// Generate directly from file
|
||||
svgData, err := freeze.GenerateFromFile("main.go")
|
||||
|
||||
// Generate from ANSI terminal output
|
||||
ansiOutput := "\033[32m✓ SUCCESS\033[0m: Build completed"
|
||||
svgData, err := freeze.GenerateFromANSI(ansiOutput)
|
||||
|
||||
// Generate from Reader
|
||||
svgData, err := freeze.GenerateFromReader(reader, "javascript")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
os.WriteFile("main.svg", svgData, 0644)
|
||||
```
|
||||
|
||||
### 2. Multiple Output Formats
|
||||
### 3. Generate PNG Format
|
||||
|
||||
```go
|
||||
// Generate SVG
|
||||
svgData, err := freeze.GenerateFromCode(code, "go")
|
||||
|
||||
// Generate PNG
|
||||
// Generate PNG instead of SVG
|
||||
pngData, err := freeze.GeneratePNGFromCode(code, "go")
|
||||
|
||||
// Save directly to file
|
||||
err := freeze.SaveCodeToFile(code, "go", "output.svg")
|
||||
err := freeze.SaveCodeToFile(code, "go", "output.png") // Auto-detect format
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
os.WriteFile("hello.png", pngData, 0644)
|
||||
```
|
||||
|
||||
### 3. Preset Configurations
|
||||
### 4. Save Directly to File
|
||||
|
||||
```go
|
||||
// Use preset configurations
|
||||
// One step: generate and save
|
||||
err := freeze.SaveCodeToFile(code, "go", "output.svg")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Auto-detect format (by file extension)
|
||||
err = freeze.SaveCodeToFile(code, "go", "output.png")
|
||||
```
|
||||
|
||||
## Using Preset Styles
|
||||
|
||||
```go
|
||||
// Use preset configurations for quick start
|
||||
freeze := freezelib.NewWithPreset("dark") // Dark theme
|
||||
freeze := freezelib.NewWithPreset("terminal") // Terminal style
|
||||
freeze := freezelib.NewWithPreset("presentation") // Presentation style
|
||||
|
||||
// Available presets
|
||||
presets := []string{
|
||||
"base", // Basic style
|
||||
"full", // macOS style
|
||||
"terminal", // Terminal optimized
|
||||
"presentation", // Presentation optimized
|
||||
"minimal", // Minimal style
|
||||
"dark", // Dark theme
|
||||
"light", // Light theme
|
||||
"retro", // Retro style
|
||||
"neon", // Neon style
|
||||
"compact", // Compact style
|
||||
}
|
||||
// View all available presets
|
||||
presets := freeze.GetAvailablePresets()
|
||||
// Returns: ["base", "compact", "dark", "full", "light", "minimal", "neon", "presentation", "retro", "terminal"]
|
||||
```
|
||||
|
||||
### 4. Custom Configuration
|
||||
## Custom Styling
|
||||
|
||||
### Basic Settings
|
||||
|
||||
```go
|
||||
config := freezelib.DefaultConfig()
|
||||
freeze := freezelib.New().
|
||||
WithTheme("github-dark"). // Set theme
|
||||
WithFont("JetBrains Mono", 14). // Set font and size
|
||||
WithBackground("#1e1e1e"). // Set background color
|
||||
WithPadding(20) // Set padding
|
||||
|
||||
// Basic settings
|
||||
config.SetTheme("github-dark")
|
||||
config.SetFont("JetBrains Mono", 14)
|
||||
config.SetBackground("#1e1e1e")
|
||||
config.SetLanguage("python")
|
||||
|
||||
// Layout settings
|
||||
config.SetPadding(20) // All sides
|
||||
config.SetPadding(20, 40) // Vertical, horizontal
|
||||
config.SetPadding(20, 40, 20, 40) // Top, right, bottom, left
|
||||
config.SetMargin(15)
|
||||
config.SetDimensions(800, 600)
|
||||
|
||||
// Decorative effects
|
||||
config.SetWindow(true) // Window controls
|
||||
config.SetLineNumbers(true) // Line numbers
|
||||
config.SetShadow(20, 0, 10) // Shadow: blur, X offset, Y offset
|
||||
config.SetBorder(1, 8, "#333") // Border: width, radius, color
|
||||
|
||||
// Line range (1-indexed)
|
||||
config.SetLines(10, 20) // Only capture lines 10-20
|
||||
|
||||
freeze := freezelib.NewWithConfig(config)
|
||||
svgData, err := freeze.GenerateFromCode(code, "go")
|
||||
```
|
||||
|
||||
## 🎨 Supported Themes
|
||||
|
||||
- `github` / `github-dark`
|
||||
- `dracula`
|
||||
- `monokai`
|
||||
- `solarized-dark` / `solarized-light`
|
||||
- `nord`
|
||||
- `one-dark`
|
||||
- `material`
|
||||
- `vim`
|
||||
- And more...
|
||||
|
||||
## 💻 Supported Languages
|
||||
|
||||
Supports 100+ programming languages including:
|
||||
- Go, Rust, Python, JavaScript, TypeScript
|
||||
- C, C++, C#, Java, Kotlin, Swift
|
||||
- HTML, CSS, SCSS, JSON, YAML, XML
|
||||
- Shell, PowerShell, Dockerfile
|
||||
- SQL, GraphQL, Markdown
|
||||
- And more...
|
||||
|
||||
## 🔧 Advanced Usage
|
||||
|
||||
### Batch Processing
|
||||
### Add Decorative Effects
|
||||
|
||||
```go
|
||||
files := []string{"main.go", "config.go", "utils.go"}
|
||||
freeze := freezelib.New().
|
||||
WithTheme("dracula").
|
||||
WithWindow(true). // Add window controls
|
||||
WithLineNumbers(true). // Show line numbers
|
||||
WithShadow(20, 0, 10) // Add shadow
|
||||
|
||||
for _, file := range files {
|
||||
svgData, err := freeze.GenerateFromFile(file)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
outputFile := strings.TrimSuffix(file, ".go") + ".svg"
|
||||
os.WriteFile(outputFile, svgData, 0644)
|
||||
}
|
||||
svgData, err := freeze.GenerateFromCode(code, "python")
|
||||
```
|
||||
|
||||
### Terminal Output Screenshots
|
||||
## View Supported Options
|
||||
|
||||
```go
|
||||
freeze := freezelib.New()
|
||||
|
||||
// View all supported languages (270+)
|
||||
languages := freeze.GetSupportedLanguages()
|
||||
fmt.Printf("Supports %d languages\n", len(languages))
|
||||
|
||||
// View all supported themes (67+)
|
||||
themes := freeze.GetSupportedThemes()
|
||||
fmt.Printf("Supports %d themes\n", len(themes))
|
||||
|
||||
// View all available presets (10)
|
||||
presets := freeze.GetAvailablePresets()
|
||||
fmt.Printf("Available presets: %v\n", presets)
|
||||
```
|
||||
|
||||
## Terminal Output Screenshots
|
||||
|
||||
```go
|
||||
// Screenshot terminal output (supports ANSI colors)
|
||||
freeze := freezelib.NewWithPreset("terminal")
|
||||
|
||||
ansiOutput := "\033[32m✓ Tests passed\033[0m\n" +
|
||||
@@ -193,72 +149,86 @@ ansiOutput := "\033[32m✓ Tests passed\033[0m\n" +
|
||||
"\033[33m⚠ Warning: deprecated API\033[0m"
|
||||
|
||||
svgData, err := freeze.GenerateFromANSI(ansiOutput)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
os.WriteFile("terminal.svg", svgData, 0644)
|
||||
```
|
||||
|
||||
### Method Chaining
|
||||
## Batch Processing Files
|
||||
|
||||
```go
|
||||
freeze := freezelib.New().
|
||||
WithTheme("monokai").
|
||||
WithFont("Cascadia Code", 15).
|
||||
WithWindow(true).
|
||||
WithShadow(20, 0, 10).
|
||||
WithLineNumbers(true)
|
||||
freeze := freezelib.NewWithPreset("dark")
|
||||
files := []string{"main.go", "config.go", "utils.go"}
|
||||
|
||||
svgData, err := freeze.GenerateFromCode(code, "rust")
|
||||
for _, file := range files {
|
||||
err := freeze.SaveFileToFile(file, file+".svg")
|
||||
if err != nil {
|
||||
fmt.Printf("Failed to process %s: %v\n", file, err)
|
||||
continue
|
||||
}
|
||||
fmt.Printf("Generated: %s.svg\n", file)
|
||||
}
|
||||
```
|
||||
|
||||
## 📊 Performance Optimization Tips
|
||||
## Auto Language Detection
|
||||
|
||||
1. **Reuse instances**: Create one `Freeze` instance and reuse it
|
||||
2. **Choose appropriate formats**: SVG for web, PNG for presentations
|
||||
3. **Set specific dimensions**: Specifying dimensions improves performance
|
||||
4. **Batch operations**: Process multiple files in a single session
|
||||
```go
|
||||
freeze := freezelib.New()
|
||||
|
||||
## 🐛 Error Handling
|
||||
// Don't specify language, auto-detect
|
||||
code := `function hello() {
|
||||
console.log("Hello, World!");
|
||||
}`
|
||||
|
||||
// Auto-detected as JavaScript
|
||||
svgData, err := freeze.GenerateFromCodeAuto(code)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
os.WriteFile("auto.svg", svgData, 0644)
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
```go
|
||||
svgData, err := freeze.GenerateFromCode(code, "go")
|
||||
if err != nil {
|
||||
switch {
|
||||
case strings.Contains(err.Error(), "language"):
|
||||
// Language detection failed
|
||||
case strings.Contains(err.Error(), "config"):
|
||||
// Configuration error
|
||||
default:
|
||||
// Other errors
|
||||
}
|
||||
fmt.Printf("Generation failed: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Save file
|
||||
err = os.WriteFile("output.svg", svgData, 0644)
|
||||
if err != nil {
|
||||
fmt.Printf("Save failed: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println("Generated successfully!")
|
||||
```
|
||||
|
||||
## 📁 Project Structure
|
||||
## Common Themes
|
||||
|
||||
```
|
||||
freezelib/
|
||||
├── freeze.go # Main API interface
|
||||
├── config.go # Configuration structs
|
||||
├── generator.go # Core generation logic
|
||||
├── quickfreeze.go # Simplified API
|
||||
├── presets.go # Preset configurations
|
||||
├── ansi.go # ANSI processing
|
||||
├── svg/ # SVG processing
|
||||
├── font/ # Font processing
|
||||
├── example/ # Usage examples
|
||||
└── README.md # Detailed documentation
|
||||
```
|
||||
- `github` - GitHub light theme
|
||||
- `github-dark` - GitHub dark theme
|
||||
- `dracula` - Dracula theme
|
||||
- `monokai` - Monokai theme
|
||||
- `nord` - Nord theme
|
||||
|
||||
## 🤝 Differences from Original freeze
|
||||
## Common Languages
|
||||
|
||||
| Feature | Original freeze | FreezeLib |
|
||||
|---------|----------------|-----------|
|
||||
| Usage | CLI tool | Go library |
|
||||
| Integration | Command line calls | Direct import |
|
||||
| Configuration | CLI args/config files | Go structs |
|
||||
| Extensibility | Limited | Highly extensible |
|
||||
| Performance | Process startup overhead | In-memory processing |
|
||||
|
||||
## 📝 Example Code
|
||||
|
||||
Check the complete examples in the `examples` directory:
|
||||
|
||||
This will generate multiple example SVG files showcasing various features of the library.
|
||||
- `go` - Go language
|
||||
- `python` - Python
|
||||
- `javascript` - JavaScript
|
||||
- `typescript` - TypeScript
|
||||
- `java` - Java
|
||||
- `rust` - Rust
|
||||
- `c` - C language
|
||||
- `cpp` - C++
|
||||
- `html` - HTML
|
||||
- `css` - CSS
|
||||
- `json` - JSON
|
||||
- `yaml` - YAML
|
||||
- `markdown` - Markdown
|
||||
- `bash` - Shell script
|
||||
|
218
examples/09-supported-options/main.go
Normal file
218
examples/09-supported-options/main.go
Normal file
@@ -0,0 +1,218 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/landaiqing/freezelib"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Println("📋 FreezeLib Supported Options Examples")
|
||||
fmt.Println("=======================================")
|
||||
|
||||
// Create output directory
|
||||
err := os.MkdirAll("output", 0755)
|
||||
if err != nil {
|
||||
fmt.Printf("❌ Error creating output directory: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Run examples
|
||||
languageListExample()
|
||||
themeListExample()
|
||||
presetListExample()
|
||||
generateExamples()
|
||||
}
|
||||
|
||||
// Language list example
|
||||
func languageListExample() {
|
||||
fmt.Println("\n💻 Supported Languages")
|
||||
fmt.Println("---------------------")
|
||||
|
||||
freeze := freezelib.New()
|
||||
|
||||
// Get all supported languages
|
||||
allLanguages := freeze.GetSupportedLanguages()
|
||||
fmt.Printf("📈 Total supported languages: %d\n", len(allLanguages))
|
||||
|
||||
// Show first 20 languages as examples
|
||||
fmt.Println("\n📋 First 20 supported languages:")
|
||||
for i, lang := range allLanguages[:min(20, len(allLanguages))] {
|
||||
fmt.Printf(" %2d. %s\n", i+1, lang)
|
||||
}
|
||||
|
||||
// Test language support
|
||||
testLanguages := []string{"go", "python", "javascript", "rust", "unknown-lang"}
|
||||
fmt.Println("\n🧪 Testing language support:")
|
||||
for _, lang := range testLanguages {
|
||||
supported := freeze.IsLanguageSupported(lang)
|
||||
status := "❌"
|
||||
if supported {
|
||||
status = "✅"
|
||||
}
|
||||
fmt.Printf(" %s %s\n", status, lang)
|
||||
}
|
||||
}
|
||||
|
||||
// Theme list example
|
||||
func themeListExample() {
|
||||
fmt.Println("\n🎨 Supported Themes")
|
||||
fmt.Println("------------------")
|
||||
|
||||
freeze := freezelib.New()
|
||||
|
||||
// Get all supported themes
|
||||
allThemes := freeze.GetSupportedThemes()
|
||||
fmt.Printf("📈 Total supported themes: %d\n", len(allThemes))
|
||||
|
||||
// Show first 20 themes as examples
|
||||
fmt.Println("\n📋 First 20 supported themes:")
|
||||
for i, theme := range allThemes[:min(20, len(allThemes))] {
|
||||
fmt.Printf(" %2d. %s\n", i+1, theme)
|
||||
}
|
||||
|
||||
// Test theme support
|
||||
testThemes := []string{"github", "dracula", "monokai", "unknown-theme"}
|
||||
fmt.Println("\n🧪 Testing theme support:")
|
||||
for _, theme := range testThemes {
|
||||
supported := freeze.IsThemeSupported(theme)
|
||||
status := "❌"
|
||||
if supported {
|
||||
status = "✅"
|
||||
}
|
||||
fmt.Printf(" %s %s\n", status, theme)
|
||||
}
|
||||
}
|
||||
|
||||
// Preset list example
|
||||
func presetListExample() {
|
||||
fmt.Println("\n⚙️ Available Presets")
|
||||
fmt.Println("-------------------")
|
||||
|
||||
freeze := freezelib.New()
|
||||
|
||||
// Get all available presets
|
||||
presets := freeze.GetAvailablePresets()
|
||||
fmt.Printf("📈 Total available presets: %d\n", len(presets))
|
||||
|
||||
// Show all presets
|
||||
fmt.Println("\n📋 Available presets:")
|
||||
for i, preset := range presets {
|
||||
fmt.Printf(" %2d. %s\n", i+1, preset)
|
||||
}
|
||||
|
||||
// Test preset validity
|
||||
testPresets := []string{"base", "full", "terminal", "dark", "light", "unknown-preset"}
|
||||
fmt.Println("\n🧪 Testing preset validity:")
|
||||
for _, preset := range testPresets {
|
||||
valid := freezelib.IsValidPreset(preset)
|
||||
status := "❌"
|
||||
if valid {
|
||||
status = "✅"
|
||||
}
|
||||
fmt.Printf(" %s %s\n", status, preset)
|
||||
}
|
||||
}
|
||||
|
||||
// Generate examples with different options
|
||||
func generateExamples() {
|
||||
fmt.Println("\n🎨 Generating Examples")
|
||||
fmt.Println("---------------------")
|
||||
|
||||
freeze := freezelib.New()
|
||||
|
||||
// Sample code for examples
|
||||
sampleCode := `package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
fmt.Println("Hello, World!")
|
||||
|
||||
// This is a comment
|
||||
for i := 0; i < 10; i++ {
|
||||
fmt.Printf("Count: %d\n", i)
|
||||
}
|
||||
}`
|
||||
|
||||
// Generate examples with different themes
|
||||
themes := []string{"github", "github-dark", "dracula", "monokai"}
|
||||
for _, theme := range themes {
|
||||
if !freeze.IsThemeSupported(theme) {
|
||||
continue
|
||||
}
|
||||
|
||||
fmt.Printf("🎨 Generating example with %s theme...\n", theme)
|
||||
|
||||
svgData, err := freeze.WithTheme(theme).
|
||||
WithFont("JetBrains Mono", 14).
|
||||
WithWindow(true).
|
||||
WithLineNumbers(true).
|
||||
WithShadow(15, 0, 8).
|
||||
WithPadding(20).
|
||||
GenerateFromCode(sampleCode, "go")
|
||||
|
||||
if err != nil {
|
||||
fmt.Printf("❌ Error with theme %s: %v\n", theme, err)
|
||||
continue
|
||||
}
|
||||
|
||||
filename := fmt.Sprintf("output/theme_%s.svg", theme)
|
||||
err = os.WriteFile(filename, svgData, 0644)
|
||||
if err != nil {
|
||||
fmt.Printf("❌ Error saving %s: %v\n", filename, err)
|
||||
continue
|
||||
}
|
||||
|
||||
fmt.Printf("✅ Generated: %s\n", filename)
|
||||
}
|
||||
|
||||
// Generate examples with different presets
|
||||
presets := []string{"base", "full", "terminal", "dark", "light"}
|
||||
bashCode := `#!/bin/bash
|
||||
|
||||
echo "Starting deployment..."
|
||||
|
||||
if [ ! -d "dist" ]; then
|
||||
echo "Building project..."
|
||||
npm run build
|
||||
fi
|
||||
|
||||
echo "Deploying to server..."
|
||||
rsync -av dist/ user@server:/var/www/html/
|
||||
|
||||
echo "Deployment complete!"`
|
||||
|
||||
for _, preset := range presets {
|
||||
if !freezelib.IsValidPreset(preset) {
|
||||
continue
|
||||
}
|
||||
|
||||
fmt.Printf("⚙️ Generating example with %s preset...\n", preset)
|
||||
|
||||
presetFreeze := freezelib.NewWithPreset(preset)
|
||||
svgData, err := presetFreeze.GenerateFromCode(bashCode, "bash")
|
||||
if err != nil {
|
||||
fmt.Printf("❌ Error with preset %s: %v\n", preset, err)
|
||||
continue
|
||||
}
|
||||
|
||||
filename := fmt.Sprintf("output/preset_%s.svg", preset)
|
||||
err = os.WriteFile(filename, svgData, 0644)
|
||||
if err != nil {
|
||||
fmt.Printf("❌ Error saving %s: %v\n", filename, err)
|
||||
continue
|
||||
}
|
||||
|
||||
fmt.Printf("✅ Generated: %s\n", filename)
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
@@ -42,6 +42,19 @@ This directory contains comprehensive examples demonstrating various features of
|
||||
- Automated workflows
|
||||
- Bulk operations
|
||||
|
||||
### [08-auto-language-detection/](08-auto-language-detection/) - Auto Language Detection
|
||||
- Content-based language detection
|
||||
- Filename-based detection
|
||||
- Custom detector configuration
|
||||
- Detection API usage
|
||||
|
||||
### [09-supported-options/](09-supported-options/) - Supported Options
|
||||
- Get all supported languages list
|
||||
- Get all supported themes list
|
||||
- Get all available presets list
|
||||
- Validate language, theme, preset support
|
||||
- Simple and efficient API
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
To run all examples:
|
||||
@@ -54,54 +67,19 @@ go run run_all_examples.go
|
||||
To run specific category:
|
||||
|
||||
```bash
|
||||
# Basic usage
|
||||
cd examples/01-basic
|
||||
go run main.go
|
||||
|
||||
# Auto language detection
|
||||
cd examples/08-auto-language-detection
|
||||
go run main.go
|
||||
|
||||
# Supported options
|
||||
cd examples/09-supported-options
|
||||
go run main.go
|
||||
```
|
||||
|
||||
## 📊 Output Formats
|
||||
|
||||
Each example category demonstrates:
|
||||
- **SVG**: Vector format, perfect for web and documentation
|
||||
- **PNG**: Raster format, ideal for presentations and social media
|
||||
- **Quality comparisons**: Different settings and their effects
|
||||
|
||||
## 🎨 Visual Features Demonstrated
|
||||
|
||||
- **Syntax Highlighting**: 100+ programming languages
|
||||
- **Themes**: Light, dark, and custom themes
|
||||
- **Window Decorations**: macOS-style window controls
|
||||
- **Line Numbers**: Optional line numbering
|
||||
- **Shadows and Borders**: Visual enhancement effects
|
||||
- **Custom Fonts**: Typography options
|
||||
- **ANSI Colors**: Terminal output rendering
|
||||
- **Responsive Sizing**: Adaptive dimensions
|
||||
|
||||
## 📝 Code Examples Include
|
||||
|
||||
- **Web Development**: HTML, CSS, JavaScript, TypeScript
|
||||
- **Backend**: Go, Python, Java, C#, Rust
|
||||
- **Mobile**: Swift, Kotlin, Dart
|
||||
- **DevOps**: Docker, YAML, Shell scripts
|
||||
- **Data**: SQL, JSON, CSV processing
|
||||
- **Documentation**: Markdown, configuration files
|
||||
|
||||
## 🔧 Configuration Examples
|
||||
|
||||
Each category includes examples of:
|
||||
- Basic configuration
|
||||
- Advanced customization
|
||||
- Performance optimization
|
||||
- Error handling
|
||||
- Best practices
|
||||
|
||||
## 📖 Learning Path
|
||||
|
||||
1. **Start with [01-basic/](01-basic/)** - Learn fundamental concepts
|
||||
2. **Explore [02-formats/](02-formats/)** - Understand output options
|
||||
3. **Try [03-themes/](03-themes/)** - Discover visual styles
|
||||
4. **Check [04-languages/](04-languages/)** - See language support
|
||||
5. **Advanced topics** - Dive into specialized use cases
|
||||
|
||||
## 🤝 Contributing Examples
|
||||
|
||||
To add new examples:
|
||||
|
@@ -42,6 +42,20 @@
|
||||
- 自动化工作流
|
||||
- 批量操作
|
||||
|
||||
### [08-auto-language-detection/](08-auto-language-detection/) - 自动语言检测
|
||||
- 智能语言检测
|
||||
- 内容分析检测
|
||||
- 文件名检测
|
||||
- 自定义检测器配置
|
||||
- 检测 API 使用
|
||||
|
||||
### [09-supported-options/](09-supported-options/) - 支持选项列表
|
||||
- 获取所有支持的语言列表
|
||||
- 获取所有支持的主题列表
|
||||
- 获取所有可用的预设列表
|
||||
- 验证语言、主题、预设支持
|
||||
- 简单高效的 API
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
运行所有示例:
|
||||
@@ -54,53 +68,20 @@ go run run_all_examples.go
|
||||
运行特定分类:
|
||||
|
||||
```bash
|
||||
# 基础示例
|
||||
cd examples/01-basic
|
||||
go run main.go
|
||||
|
||||
# 自动语言检测
|
||||
cd examples/08-auto-language-detection
|
||||
go run main.go
|
||||
|
||||
# 支持选项列表
|
||||
cd examples/09-supported-options
|
||||
go run main.go
|
||||
```
|
||||
|
||||
## 📊 输出格式
|
||||
|
||||
每个示例分类都演示:
|
||||
- **SVG**: 矢量格式,完美适用于网页和文档
|
||||
- **PNG**: 栅格格式,适合演示和社交媒体
|
||||
- **质量对比**: 不同设置及其效果
|
||||
|
||||
## 🎨 展示的视觉功能
|
||||
|
||||
- **语法高亮**: 100+ 种编程语言
|
||||
- **主题**: 浅色、深色和自定义主题
|
||||
- **窗口装饰**: macOS 风格窗口控件
|
||||
- **行号**: 可选行号显示
|
||||
- **阴影和边框**: 视觉增强效果
|
||||
- **自定义字体**: 排版选项
|
||||
- **ANSI 颜色**: 终端输出渲染
|
||||
- **响应式尺寸**: 自适应尺寸
|
||||
|
||||
## 📝 代码示例包括
|
||||
|
||||
- **Web 开发**: HTML, CSS, JavaScript, TypeScript
|
||||
- **后端**: Go, Python, Java, C#, Rust
|
||||
- **移动端**: Swift, Kotlin, Dart
|
||||
- **DevOps**: Docker, YAML, Shell 脚本
|
||||
- **数据**: SQL, JSON, CSV 处理
|
||||
- **文档**: Markdown, 配置文件
|
||||
|
||||
## 🔧 配置示例
|
||||
|
||||
每个分类都包含以下示例:
|
||||
- 基本配置
|
||||
- 高级自定义
|
||||
- 性能优化
|
||||
- 错误处理
|
||||
- 最佳实践
|
||||
|
||||
## 📖 学习路径
|
||||
|
||||
1. **从 [01-basic/](01-basic/) 开始** - 学习基本概念
|
||||
2. **探索 [02-formats/](02-formats/)** - 了解输出选项
|
||||
3. **尝试 [03-themes/](03-themes/)** - 发现视觉样式
|
||||
4. **查看 [04-languages/](04-languages/)** - 了解语言支持
|
||||
5. **高级主题** - 深入专业用例
|
||||
|
||||
## 🤝 贡献示例
|
||||
|
||||
|
58
freeze.go
58
freeze.go
@@ -10,6 +10,10 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"sort"
|
||||
|
||||
"github.com/alecthomas/chroma/v2/lexers"
|
||||
"github.com/alecthomas/chroma/v2/styles"
|
||||
)
|
||||
|
||||
// Freeze is the main interface for generating code screenshots
|
||||
@@ -358,9 +362,11 @@ func (f *Freeze) DetectLanguageFromFile(filename, content string) string {
|
||||
return f.generator.DetectLanguageFromFile(filename, content)
|
||||
}
|
||||
|
||||
// GetSupportedLanguages returns a list of all supported languages
|
||||
// GetSupportedLanguages returns a sorted list of all supported programming languages
|
||||
func (f *Freeze) GetSupportedLanguages() []string {
|
||||
return f.generator.GetSupportedLanguages()
|
||||
languages := lexers.Names(false)
|
||||
sort.Strings(languages)
|
||||
return languages
|
||||
}
|
||||
|
||||
// IsLanguageSupported checks if a language is supported
|
||||
@@ -379,11 +385,59 @@ func (f *Freeze) GetLanguageDetector() *LanguageDetector {
|
||||
return f.generator.GetLanguageDetector()
|
||||
}
|
||||
|
||||
// GetSupportedThemes returns a sorted list of all supported themes
|
||||
func (f *Freeze) GetSupportedThemes() []string {
|
||||
var themes []string
|
||||
for name := range styles.Registry {
|
||||
themes = append(themes, name)
|
||||
}
|
||||
sort.Strings(themes)
|
||||
return themes
|
||||
}
|
||||
|
||||
// IsThemeSupported checks if a theme is supported
|
||||
func (f *Freeze) IsThemeSupported(theme string) bool {
|
||||
return f.generator.IsThemeSupported(theme)
|
||||
}
|
||||
|
||||
// GetAvailablePresets returns a sorted list of all available presets
|
||||
func (f *Freeze) GetAvailablePresets() []string {
|
||||
presets := ListPresets()
|
||||
sort.Strings(presets)
|
||||
return presets
|
||||
}
|
||||
|
||||
// isPNGFile checks if the filename has a PNG extension
|
||||
func isPNGFile(filename string) bool {
|
||||
return len(filename) > 4 && filename[len(filename)-4:] == ".png"
|
||||
}
|
||||
|
||||
// Global convenience functions for accessing supported options
|
||||
|
||||
// GetSupportedLanguages returns a sorted list of all supported programming languages
|
||||
func GetSupportedLanguages() []string {
|
||||
languages := lexers.Names(false)
|
||||
sort.Strings(languages)
|
||||
return languages
|
||||
}
|
||||
|
||||
// GetSupportedThemes returns a sorted list of all supported themes
|
||||
func GetSupportedThemes() []string {
|
||||
var themes []string
|
||||
for name := range styles.Registry {
|
||||
themes = append(themes, name)
|
||||
}
|
||||
sort.Strings(themes)
|
||||
return themes
|
||||
}
|
||||
|
||||
// GetAvailablePresets returns a sorted list of all available presets
|
||||
func GetAvailablePresets() []string {
|
||||
presets := ListPresets()
|
||||
sort.Strings(presets)
|
||||
return presets
|
||||
}
|
||||
|
||||
// Version information
|
||||
const (
|
||||
Version = "1.0.0"
|
||||
|
10
generator.go
10
generator.go
@@ -120,6 +120,16 @@ func (g *Generator) GetLanguageDetector() *LanguageDetector {
|
||||
return g.languageDetector
|
||||
}
|
||||
|
||||
// GetSupportedThemes returns a list of all supported themes
|
||||
func (g *Generator) GetSupportedThemes() []string {
|
||||
return g.languageDetector.GetSupportedThemes()
|
||||
}
|
||||
|
||||
// IsThemeSupported checks if a theme is supported
|
||||
func (g *Generator) IsThemeSupported(theme string) bool {
|
||||
return g.languageDetector.IsThemeSupported(theme)
|
||||
}
|
||||
|
||||
// GenerateFromANSI generates an SVG from ANSI terminal output
|
||||
func (g *Generator) GenerateFromANSI(ansiOutput string) ([]byte, error) {
|
||||
if err := g.config.Validate(); err != nil {
|
||||
|
@@ -6,6 +6,7 @@ import (
|
||||
|
||||
"github.com/alecthomas/chroma/v2"
|
||||
"github.com/alecthomas/chroma/v2/lexers"
|
||||
"github.com/alecthomas/chroma/v2/styles"
|
||||
)
|
||||
|
||||
// LanguageDetector provides enhanced language detection capabilities
|
||||
@@ -168,6 +169,21 @@ func (ld *LanguageDetector) GetSupportedLanguages() []string {
|
||||
return lexers.Names(false) // false means don't include aliases
|
||||
}
|
||||
|
||||
// GetSupportedThemes returns a list of all supported themes
|
||||
func (ld *LanguageDetector) GetSupportedThemes() []string {
|
||||
var themes []string
|
||||
for name := range styles.Registry {
|
||||
themes = append(themes, name)
|
||||
}
|
||||
return themes
|
||||
}
|
||||
|
||||
// IsThemeSupported checks if a theme is supported
|
||||
func (ld *LanguageDetector) IsThemeSupported(theme string) bool {
|
||||
_, exists := styles.Registry[strings.ToLower(theme)]
|
||||
return exists
|
||||
}
|
||||
|
||||
// IsLanguageSupported checks if a language is supported
|
||||
func (ld *LanguageDetector) IsLanguageSupported(language string) bool {
|
||||
lexer := lexers.Get(language)
|
||||
|
@@ -241,3 +241,90 @@ func TestLanguageSupport(t *testing.T) {
|
||||
t.Error("Nonexistent language should not be supported")
|
||||
}
|
||||
}
|
||||
|
||||
func TestThemeSupport(t *testing.T) {
|
||||
freeze := New()
|
||||
|
||||
// Test supported themes
|
||||
themes := freeze.GetSupportedThemes()
|
||||
if len(themes) == 0 {
|
||||
t.Error("No supported themes found")
|
||||
}
|
||||
|
||||
// Test common themes
|
||||
commonThemes := []string{"github", "github-dark", "monokai", "dracula"}
|
||||
for _, theme := range commonThemes {
|
||||
if !freeze.IsThemeSupported(theme) {
|
||||
t.Errorf("Theme %s should be supported", theme)
|
||||
}
|
||||
}
|
||||
|
||||
// Test unsupported theme
|
||||
if freeze.IsThemeSupported("nonexistent-theme") {
|
||||
t.Error("Nonexistent theme should not be supported")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPresetSupport(t *testing.T) {
|
||||
freeze := New()
|
||||
|
||||
// Test available presets
|
||||
presets := freeze.GetAvailablePresets()
|
||||
if len(presets) == 0 {
|
||||
t.Error("No available presets found")
|
||||
}
|
||||
|
||||
// Test common presets
|
||||
commonPresets := []string{"base", "full", "terminal", "dark", "light"}
|
||||
for _, preset := range commonPresets {
|
||||
if !IsValidPreset(preset) {
|
||||
t.Errorf("Preset %s should be valid", preset)
|
||||
}
|
||||
}
|
||||
|
||||
// Test invalid preset
|
||||
if IsValidPreset("nonexistent-preset") {
|
||||
t.Error("Nonexistent preset should not be valid")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistry(t *testing.T) {
|
||||
freeze := New()
|
||||
registry := freeze.GetRegistry()
|
||||
|
||||
// Test popular languages
|
||||
popularLangs := registry.GetPopularLanguages()
|
||||
if len(popularLangs) == 0 {
|
||||
t.Error("No popular languages found")
|
||||
}
|
||||
|
||||
// Test popular themes
|
||||
popularThemes := registry.GetPopularThemes()
|
||||
if len(popularThemes) == 0 {
|
||||
t.Error("No popular themes found")
|
||||
}
|
||||
|
||||
// Test dark themes
|
||||
darkThemes := registry.GetDarkThemes()
|
||||
if len(darkThemes) == 0 {
|
||||
t.Error("No dark themes found")
|
||||
}
|
||||
|
||||
// Test light themes
|
||||
lightThemes := registry.GetLightThemes()
|
||||
if len(lightThemes) == 0 {
|
||||
t.Error("No light themes found")
|
||||
}
|
||||
|
||||
// Test statistics
|
||||
stats := registry.GetStatistics()
|
||||
if stats["Languages"] == 0 {
|
||||
t.Error("Language count should be greater than 0")
|
||||
}
|
||||
if stats["Themes"] == 0 {
|
||||
t.Error("Theme count should be greater than 0")
|
||||
}
|
||||
if stats["Presets"] == 0 {
|
||||
t.Error("Preset count should be greater than 0")
|
||||
}
|
||||
}
|
||||
|
@@ -241,6 +241,23 @@ func (qf *QuickFreeze) IsLanguageSupported(language string) bool {
|
||||
return generator.IsLanguageSupported(language)
|
||||
}
|
||||
|
||||
// GetSupportedThemes returns a list of all supported themes
|
||||
func (qf *QuickFreeze) GetSupportedThemes() []string {
|
||||
generator := NewGenerator(qf.config)
|
||||
return generator.GetSupportedThemes()
|
||||
}
|
||||
|
||||
// IsThemeSupported checks if a theme is supported
|
||||
func (qf *QuickFreeze) IsThemeSupported(theme string) bool {
|
||||
generator := NewGenerator(qf.config)
|
||||
return generator.IsThemeSupported(theme)
|
||||
}
|
||||
|
||||
// GetAvailablePresets returns a list of all available presets
|
||||
func (qf *QuickFreeze) GetAvailablePresets() []string {
|
||||
return GetAvailablePresets()
|
||||
}
|
||||
|
||||
// FileToSVG generates SVG from a source code file
|
||||
func (qf *QuickFreeze) FileToSVG(filename string) ([]byte, error) {
|
||||
generator := NewGenerator(qf.config)
|
||||
|
Reference in New Issue
Block a user