golang终端应用高级ANSI样式与颜色支持插件库termenv的使用

Golang终端应用高级ANSI样式与颜色支持插件库termenv的使用

termenv是一个Golang库,可让您安全地在终端上使用高级样式选项。它能收集终端环境的ANSI和颜色支持信息,并为您提供方便的方法来为输出着色和添加样式,而无需处理各种奇怪的ANSI转义序列和颜色转换。

termenv Logo

主要特性

  • 支持RGB/TrueColor
  • 检测终端支持的颜色范围
  • 自动将颜色转换为最佳匹配的可用颜色
  • 终端主题(浅色/深色)检测
  • 链式语法
  • 嵌套样式

安装

go get github.com/muesli/termenv

基本用法

package main

import (
	"fmt"
	"os"

	"github.com/muesli/termenv"
)

func main() {
	// 创建输出对象
	output := termenv.NewOutput(os.Stdout)

	// 获取终端支持的profile
	profile := output.Profile
	fmt.Printf("终端支持的颜色profile: %v\n", profile)

	// 检查终端背景是否为深色
	darkTheme := output.HasDarkBackground()
	fmt.Printf("终端使用深色背景: %v\n", darkTheme)

	// 创建带样式的字符串
	s := output.String("Hello World")

	// 设置前景色(支持hex值)
	s = s.Foreground(output.Color("#abcdef"))
	// 设置背景色(支持ANSI颜色0-255)
	s = s.Background(output.Color("69"))

	// 输出带样式的字符串
	fmt.Println(s)
}

颜色支持

termenv支持多种颜色profile:Ascii(仅黑白)、ANSI(16色)、ANSI Extended(256色)和TrueColor(24位RGB)。颜色将自动降级为所需profile中最匹配的可用颜色:

TrueColor => ANSI 256 Colors => ANSI 16 Colors => Ascii

// 创建带样式的字符串
s := output.String("Hello World")

// 支持hex值
// 在不支持RGB的终端上会自动降级颜色
s.Foreground(output.Color("#abcdef"))
// 也支持ANSI颜色(0-255)
s.Background(output.Color("69"))
// 或color.Color接口
s.Foreground(output.FromColor(color.RGBA{255, 128, 0, 255}))

// 组合前景和背景色
s.Foreground(output.Color("#ffffff")).Background(output.Color("#0000ff"))

// 支持fmt.Stringer接口
fmt.Println(s)

文本样式

您可以使用链式语法组合自己的样式:

s := output.String("foobar")

// 文本样式
s.Bold()     // 粗体
s.Faint()    // 淡色
s.Italic()   // 斜体
s.CrossOut() // 删除线
s.Underline() // 下划线
s.Overline()  // 上划线

// 反转当前前景和背景色
s.Reverse()

// 闪烁文本
s.Blink()

// 组合多个选项
s.Bold().Underline()

完整示例

以下是一个完整的示例,展示了termenv的主要功能:

package main

import (
	"fmt"
	"image/color"
	"os"

	"github.com/muesli/termenv"
)

func main() {
	// 初始化输出
	output := termenv.NewOutput(os.Stdout)

	// 检测终端特性
	fmt.Println("终端特性检测:")
	fmt.Printf("Profile: %v\n", output.Profile)
	fmt.Printf("支持深色背景: %v\n", output.HasDarkBackground())
	fmt.Printf("前景色: %v\n", output.ForegroundColor())
	fmt.Printf("背景色: %v\n", output.BackgroundColor())

	// 基本样式示例
	fmt.Println("\n基本样式示例:")
	fmt.Println(output.String("普通文本"))
	fmt.Println(output.String("粗体文本").Bold())
	fmt.Println(output.String("斜体文本").Italic())
	fmt.Println(output.String("下划线文本").Underline())
	fmt.Println(output.String("删除线文本").CrossOut())
	fmt.Println(output.String("闪烁文本").Blink())

	// 颜色示例
	fmt.Println("\n颜色示例:")
	fmt.Println(output.String("红色文本").Foreground(output.Color("#ff0000")))
	fmt.Println(output.String("绿色背景").Background(output.Color("#00ff00")))
	fmt.Println(output.String("蓝色前景黄色背景").
		Foreground(output.Color("#0000ff")).
		Background(output.Color("#ffff00")))

	// 使用color.Color接口
	fmt.Println("\n使用color.Color接口:")
	c := color.RGBA{255, 0, 255, 255} // 洋红色
	fmt.Println(output.String("洋红色文本").Foreground(output.FromColor(c)))

	// 链式调用
	fmt.Println("\n链式调用示例:")
	styled := output.String("粗体+斜体+下划线+红色").
		Bold().
		Italic().
		Underline().
		Foreground(output.Color("#ff0000"))
	fmt.Println(styled)

	// 终端控制
	fmt.Println("\n终端控制示例:")
	output.MoveCursor(5, 0) // 移动光标到第5行开头
	fmt.Println("这行文本出现在第5行")
	output.CursorUp(2)     // 光标上移2行
	fmt.Println("这行文本出现在第3行")
	output.ClearLine()     // 清除当前行
}

终端控制

termenv还提供了丰富的终端控制功能:

// 移动光标到指定位置
output.MoveCursor(row, column)

// 保存光标位置
output.SaveCursorPosition()

// 恢复保存的光标位置
output.RestoreCursorPosition()

// 清除屏幕
output.ClearScreen()

// 清除当前行
output.ClearLine()

// 切换到备用屏幕
output.AltScreen()

// 退出备用屏幕
output.ExitAltScreen()

// 隐藏光标
output.HideCursor()

// 显示光标
output.ShowCursor()

Windows支持

在Windows上,您需要先启用ANSI处理:

restoreConsole, err := termenv.EnableVirtualTerminalProcessing(termenv.DefaultOutput())
if err != nil {
    panic(err)
}
defer restoreConsole()

termenv是一个功能强大且易于使用的终端样式库,可以帮助您创建美观的命令行应用程序。


更多关于golang终端应用高级ANSI样式与颜色支持插件库termenv的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang终端应用高级ANSI样式与颜色支持插件库termenv的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


使用termenv实现Golang终端应用的高级ANSI样式与颜色支持

termenv是一个强大的Go库,用于在终端应用程序中实现高级ANSI样式和颜色支持。它提供了跨平台的终端样式功能,自动检测终端能力并优雅降级。

安装termenv

go get github.com/muesli/termenv

基础使用

1. 基本颜色输出

package main

import (
	"fmt"
	"github.com/muesli/termenv"
)

func main() {
	// 获取颜色配置文件
	p := termenv.ColorProfile()

	// 创建带颜色的输出
	red := termenv.String("红色文字").Foreground(p.Color("#FF0000"))
	green := termenv.String("绿色文字").Foreground(p.Color("#00FF00"))
	blue := termenv.String("蓝色文字").Foreground(p.Color("#0000FF"))

	fmt.Println(red, green, blue)
}

2. 样式组合

func styleExample() {
	output := termenv.String("粗体+下划线+红色背景+黄色文字")
	output = output.
		Bold().
		Underline().
		Foreground(termenv.ANSIYellow).
		Background(termenv.ANSIRed)

	fmt.Println(output)
}

高级功能

1. 检测终端支持

func terminalSupport() {
	// 检测终端是否支持真彩色
	if termenv.HasTrueColor() {
		fmt.Println("终端支持真彩色")
	}

	// 获取当前颜色配置文件
	profile := termenv.EnvColorProfile()
	fmt.Printf("当前颜色配置: %v\n", profile)
}

2. 渐变色文字

func gradientText() {
	text := "渐变色文字效果"
	gradient := termenv.String(text)

	// 创建渐变效果
	for i, c := range text {
		// 计算颜色值 (HSV色轮)
		hue := float64(i) * 360.0 / float64(len(text))
		color := termenv.HSVColor(hue, 1.0, 1.0)
		gradient = gradient.ColorRune(i, color)
	}

	fmt.Println(gradient)
}

3. 进度条实现

func progressBar() {
	const width = 50
	p := termenv.ColorProfile()

	for i := 0; i <= width; i++ {
		// 构建进度条
		bar := termenv.String("[").
			Foreground(p.Color("#FFFFFF")) +
			termenv.String(strings.Repeat("=", i)).
				Foreground(p.Color("#00FF00")) +
			termenv.String(strings.Repeat(" ", width-i)).
				Foreground(p.Color("#333333")) +
			termenv.String("]").
				Foreground(p.Color("#FFFFFF"))

		// 添加百分比
		percent := termenv.String(fmt.Sprintf(" %3.0f%%", float64(i)/width*100)).
			Foreground(p.Color("#FFFFFF"))

		// 移动光标到行首并输出
		fmt.Printf("\r%s%s", bar, percent)
		time.Sleep(100 * time.Millisecond)
	}
	fmt.Println()
}

4. 主题支持

func themeExample() {
	// 创建自定义主题
	theme := termenv.NewTheme()
	theme.Set("error", termenv.Style{}.Foreground(termenv.ANSIRed).Bold())
	theme.Set("success", termenv.Style{}.Foreground(termenv.ANSIGreen))
	theme.Set("warning", termenv.Style{}.Foreground(termenv.ANSIYellow))

	// 使用主题
	fmt.Println(theme.Styles["error"].Styled("错误信息"))
	fmt.Println(theme.Styles["success"].Styled("成功信息"))
	fmt.Println(theme.Styles["warning"].Styled("警告信息"))
}

实际应用示例

表格输出

func coloredTable() {
	// 表格数据
	data := [][]string{
		{"ID", "Name", "Status", "Value"},
		{"1", "Item A", "Active", "$10.00"},
		{"2", "Item B", "Inactive", "$20.50"},
		{"3", "Item C", "Pending", "$15.75"},
	}

	p := termenv.ColorProfile()
	headerColor := termenv.ANSICyan
	activeColor := termenv.ANSIGreen
	inactiveColor := termenv.ANSIYellow
	pendingColor := termenv.ANSIBlue

	for i, row := range data {
		for j, cell := range row {
			var styledCell termenv.Style
			
			// 表头样式
			if i == 0 {
				styledCell = termenv.String(cell).Foreground(headerColor).Bold()
			} else {
				// 状态列特殊处理
				if j == 2 {
					switch cell {
					case "Active":
						styledCell = termenv.String(cell).Foreground(activeColor)
					case "Inactive":
						styledCell = termenv.String(cell).Foreground(inactiveColor)
					case "Pending":
						styledCell = termenv.String(cell).Foreground(pendingColor)
					}
				} else {
					styledCell = termenv.String(cell).Foreground(p.Color("#FFFFFF"))
				}
			}
			
			fmt.Printf("%-15s", styledCell)
		}
		fmt.Println()
	}
}

注意事项

  1. 终端兼容性:termenv会自动检测终端能力并适当降级,无需手动处理
  2. 性能考虑:频繁更新终端内容时使用\r而不是\n可以减少闪烁
  3. 重置样式:termenv会自动在字符串末尾添加重置代码,无需手动添加
  4. Windows支持:termenv在Windows上也能正常工作,会自动转换为适合Windows终端的格式

termenv提供了比标准库更丰富的终端控制功能,同时保持了简单易用的API。通过合理使用这些功能,可以创建出既美观又专业的命令行应用程序。

回到顶部