Highlightr
Highlightr是使用Swift构建的iOS和macOS语法高亮显示器。它使用highlight.js作为核心,支持176种语言和79种样式。
提取带有代码的糟糕字符串并返回带有适当语法高亮的NSAttributedString。
安装
要求
- iOS 8.0+
- macOS 10.10+
CocoaPods
CocoaPods是Cocoa项目的依赖管理器。您可以使用以下命令进行安装:
$ gem install cocoapods
要使用CocoaPods将Highlightr集成到您的Xcode项目中,请在您的Podfile
中指定它:
source 'https://github.com/CocoaPods/Specs.git'
use_frameworks!
target '<Your Target Name>' do
pod 'Highlightr'
end
然后,运行以下命令:
$ pod install
Carthage
Carthage是一款去中心化的依赖管理工具,它可以构建您的依赖并提供二进制框架。
您可以使用以下命令通过Homebrew安装Carthage:
$ brew update
$ brew install carthage
要使用Carthage将Highlightr集成到您的Xcode项目中,请在其Cartfile
中指定它。
github "raspu/Highlightr"
运行carthage update
构建框架,并将构建的Highlightr.framework
拖放到您的Xcode项目中。
用法
Highlightr提供了两个主要类:
Highlightr
这是主接口,您可以使用它将代码字符串转换为NSAttributed字符串。
let highlightr = Highlightr()
highlightr.setTheme(to: "paraiso-dark")
let code = "let a = 1"
// You can omit the second parameter to use automatic language detection.
let highlightedCode = highlightr.highlight(code, as: "swift")
CodeAttributedString
它是NSTextStorage的一个子类,您可以使用它实时高亮显示文本。
let textStorage = CodeAttributedString()
textStorage.language = "Swift"
let layoutManager = NSLayoutManager()
textStorage.addLayoutManager(layoutManager)
let textContainer = NSTextContainer(size: view.bounds.size)
layoutManager.addTextContainer(textContainer)
let textView = UITextView(frame: yourFrame, textContainer: textContainer)
JavaScript?
是的,Highlightr依赖于iOS和macOS的JavaScriptCore来使用highlight.js解析代码。这实际上非常快!
性能
它可能不会像本地解决方案那样快,但它足够快,可以在实时编辑器中使用。
它内置了自定义HTML解析器,用于创建NSAttributtedStrings,预处理主题,并预加载JS库。因此,在我的iPhone 6s上处理500行代码大约需要50毫秒。
文档
您可以在cocoadocs上找到最新版本的文档。
许可
Highlightr遵循MIT许可协议。有关更多信息,请参阅LICENSE文件。
Highlight.js遵循BSD许可协议。您可以在以下链接找到许可文件:许可文件。