Syntax Highlighting for Swift and SwiftUI
Swift class to convert a String
of code into a syntax highlighted AttributedString
- 🔍 Automatic language detection
- 📚 Support for 50+ common languages
- 🌈 Choose from 30 built-in color themes or use custom CSS
- 🧰 Built with highlight.js &
JavaScriptCore
- ☑️ Complete concurrency checking enabled
- 🖥️ Works on iOS, iPadOS, macOS, and tvOS
SwiftUI view to display a String
of code with syntax highlighting
- 🌗 Color theme syncs automatically with Dark Mode
- 📜 Theme background color included with
.card
style - 🔠 Works with
Text
modifiers like.bold()
or.font()
- ⚙️ Includes modifiers to set the color theme, style & language
- 📫 Callback modifiers to get the highlight results, language & score
- 🍃 Memory efficient using an internal
Highlight
environment entry
Create an instance of Highlight
and convert a String
of code into a syntax highlighted AttributedString
:
let someCode = """
print(\"Hello World\")
"""
let highlight = Highlight()
let attributedText = try await highlight.attributedText(someCode)
Add the language:
parameter to set the language and disable automatic language detection:
let attributedText = try await highlight.attributedText(someCode, language: "swift")
Use the colors:
parameter to change the color theme.
let attributedText = try await highlight.attributedText(someCode, colors: .dark(.github))
Apply a custom CSS theme with the .custom
option.
Refer to the highlight.js Theme Guide for details:
let someCSS = """
.hljs {
display: block;
overflow-x: auto;
padding: 0.5em;
}
"""
let attributedText = try await highlight.attributedText(someCode, colors: .custom(css: someCSS))
The request
function returns a HighlightResult
struct.
This result struct includes details such as the detected language along with the attributed text:
let result: HighlightResult = try await highlight.request(someCode)
print(result)
HighlightResult(
attributedText: "...",
relevance: 5,
language: "swift",
languageName: "Swift?",
backgroundColor: #1F2024FF,
hasIllegal: false,
isUndefined: false)
Create a CodeText
view with some code:
let someCode: String = """
print(\"Hello World\")
"""
var body: some View {
CodeText(someCode)
}
The font design is always .monospaced
.
Other text modifiers can be applied as usual:
CodeText(someCode)
.font(.callout)
.fontWeight(.semibold)
Add the .highlightLanguage(_:)
modifier to set the language and disable automatic detection:
CodeText(someCode)
.highlightLanguage(.swift)
Add the .codeTextColors(_:)
modifier to set the color theme. The built-in color themes update automatically with Dark Mode to the corresponding dark variant.
CodeText(someCode)
.codeTextColors(.github)
Choose the .custom
option to use any custom CSS color theme. Refer to the official highlight.js Theme Guide for more info.
CodeText(someCode)
.codeTextColors(.custom(dark: .custom(css: someDarkCSS), light: .custom(css: someLightCSS)))
The default style is .plain
without any background or padding. Some of the color themes are more legible with their corresponding background color. Add the .codeTextStyle(_:)
modifier and choose the .card
style to show the background:
CodeText(someCode)
.codeTextStyle(.card)
The .card
style has a few customization options, for example:
CodeText(someCode)
.codeTextStyle(.card(cornerRadius: 0, stroke: .separator, verticalPadding: 12))
Add .onHighlightSuccess(_:)
to get the highlight results, including the detected language, relevancy score, background color and other details. Unexpected errors are unlikely but can be handled with .onHighlightFailure(_:)
if necessary for debugging.
CodeText(someCode)
.onHighlightSuccess { result in
...
}
.onHighlightFailure { error in
...
}
There is also a combined .onHighlightResult(_:)
equivalent of the two callbacks above.
CodeText(someCode)
.onHighlightResult { result in
switch result {
case .success:
...
case .failure:
...
}
}
It is notable that a failure to match a language to the input is actually not a highlight failure. Rather the result will have isUndefined
set to true
and the language will be "unknown" with a relevance score of zero.
A previously stored highlight result can be passed to the CodeText
.
This in combination with .onHighlightSuccess(_:)
enables persistence of the result when the view might reappear frequently, such as in a list view:
let someCode: String = """
print(\"Hello World\")
"""
@State var result: HighlightResult?
var body: some View {
List {
...
CodeText(someCode, result: result)
.onHighlightSuccess { result in
self.result = result
}
...
}
}
- In Xcode, go to
File
>Add packages...
- Enter
https://github.com/appstefan/highlightswift
in the field and clickAdd Package
In Package.swift
add this repository as a dependency:
dependencies: [
.package(url: "https://github.com/appstefan/highlightswift.git", from: "1.1")
],
targets: [
.target(
name: "YourPackageName",
dependencies: ["HighlightSwift"]
)
]
Stefan, thrower_ranges.0d@icloud.com
HighlightSwift is available under the MIT license. See the LICENSE.md file. Highlight.js is available under the BSD license. See the LICENSE.md file.