はじめに
検索できるChatGPT「ThinkMate」でシンタックスハイライトに対応しました。
今回は、そこで使用した技術をご紹介します。
作るもの
準備
Swift Package ManagerでSplashというライブラリをインストールします。
実装方法
以下は、Swiftのコードをシンタックスハイライトで表示するコードです。
import SwiftUI
import Splash
struct ContentView: View {
let code = """
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
Text("Hello, world!")
}
}
}
"""
var body: some View {
codeView(code)
}
private func codeView(_ code: String) -> some View {
let theme = Theme(
font: Font(size: 20),
plainTextColor: UIColor(.primary),
tokenColors: [
.keyword: UIColor(.pink),
.string: UIColor(.orange),
.type: UIColor(.indigo),
.call: UIColor(.purple),
.number: UIColor(.yellow),
.comment: UIColor.lightGray,
.property: UIColor(.teal),
.dotAccess: UIColor(.teal),
.preprocessing: UIColor.darkGray
]
)
let highlighter = SyntaxHighlighter(
format: AttributedStringOutputFormat(theme: theme)
)
let attributedString = AttributedString(highlighter.highlight(code))
return Text(attributedString)
}
}
Splashというライブラリを使ってシンタックスハイライトを実現しました。
ポイントは以下の3点です。
- Themeで色を指定
- SyntaxHighlighterでハイライト
- SyntaxHighlighter.highlightはNSAttributedStringであるため、Textで使えるAttributedStringに変換
おわり
以上のコードを実行することで、コードビューアができあがります。
ご覧いただきありがとうございました。