Terminus 的目标是让编写视觉上吸引人的命令行应用程序变得快速、高效和直观。它旨在提供高级构建块,如菜单和用户提示(y/n、多项选择、REPL 等),以及对 ANSI 代码的低级访问,以便用户获得更完整的控制。
Terminal
类是一个共享的单例,它提供输出文本、移动光标和与终端交互的主要接口。 首次实例化时,输入模式设置为 .cbreak,并且回显关闭。
import Terminus
let terminal = Terminal.shared
要打印到屏幕,请使用 terminal
的写入方法之一
Terminal/write(_:attributes:)
Terminal/write(attributedString:)
.terminal.write("Hello world!")
大多数现代终端模拟器都支持文本样式和颜色(通常为 256 色)。 要将一个或多个样式添加到文本,您可以在调用 write 时传递一个属性数组。有关文本样式和颜色支持的列表,请参阅 Attribute
。
terminal.write("I am bold and underlined.\n", attributes: [.bold, .underline])
您还可以使用属性字符串来添加样式,如
var attributedString = AttributedString("Hello, bold, underlined, world.")
if let boldRange = attributedString.range(of: "bold") {
attributedString[boldRange].terminalTextAttributes = [.bold]
}
if let underlinedRange = attributedString.range(of: "underlined") {
attributedString[underlinedRange].terminalTextAttributes = [.underline]
}
terminal.write(attributedString: attributedString)
终端单元格具有前景色(通常为白色)和背景色(通常为黑色)。 可以使用 RGB 显式定义颜色,也可以从内置颜色调色板中按名称选择颜色。
您可以使用 Attribute/color(_:)
指定前景色,并使用 RGB 指定任何 Color
。
let greenColor = Color(r:0, g:255, b:0)
terminal.write("Grass is green.\n", attributes: [.color(greenColor)])
要同时设置前景色和背景色,请使用 Attribute/colorPair(_:)
并传入一个 ColorPair
。
let redColor = Color(r: 255, g:0, b:0)
let grayColor = Color(r: 200, g:200, b:200)
let redOnGray = ColorPair(foreground: redColor, background: grayColor)
terminal.write("Red rum.\n", attributes: [.colorPair(redOnGray)])
Terminus 还具有内置的颜色调色板,可用于按名称指定颜色。 调色板中的颜色就像 Terminus 中的任何其他 Color
一样传递。
let palette = XTermPalette()
let blueOneYellow = ColorPair(foreground: palette.Blue1, background: palette.Yellow1)
terminal.write("Blue on yellow", attributes: [.colorPair(blueOneYellow)])
要捕获单个按键,请使用 Terminal/getKey()
。
terminal.write("Press any key: ")
if let key = try? terminal.getKey() {
terminal.write("\nYou pressed the \(key.rawValue) key.")
}
要捕获整行文本(直到收到 "\n"),请使用 Terminal/getLine()
函数。
let line = terminal.getLine()
您可以在 Swift Package Index 上找到 DocC 文件,或者使用 XCode 或 DocC 包自行编译和查看它们。
要在您自己的基于 Swift PM 的项目中使用 Terminus
,只需将其添加为您的包和可执行目标的一个依赖项
let package = Package(
// name, platforms, products, etc.
dependencies: [
// other dependencies
.package(url: "https://github.com/jbadger3/Terminus", from: "0.1.0"),
],
targets: [
.executableTarget(name: "YourAppName", dependencies: [
// other dependencies
.product(name: "Terminus", package: "Terminus"),
]),
// other targets
]
)
在您当前的 CLI 项目中
我绝不是终端方面的专家,我也不能说我没有从其他项目中挑选我喜欢的代码片段。 包、灵感来源和有价值信息的来源包括
ConsolKit 来自 Vapor 的开发者,一个 Swift 中的 http 服务器。
commandlinekit 来自 Google 的 Matthias Zenger
Termios - 比我在这里实现的更全面的 Swifty termios 包装器。
XTerm 控制序列 我认为这是与控制台相关信息的权威来源之一。
标准 C 库 read 函数
博客 关于终端模拟器和 termios
关于内核级别的 低级输入流的缓冲
ANSI 代码 摘要
rainbow : 一个漂亮的 ANSI 文本样式包。
The TTY demystified:一篇关于 TTY 子系统的历史和内部运作的精彩文章。