Syntax Highlighting in Swift and SwiftUI
Convert any String of code into a syntax highlighted AttributedString
- 🔍 Automatic language detection
- 📚 Works with 50 common languages
- 🌈 Choose from 30 classic color themes
- 🧰 Built with highlight.js and
JavaScriptCore - 🖥️ Supported on iOS, iPadOS, macOS, and tvOS
Drop-in replacement for the SwiftUI Text view
- 🔠 Supports most
Textmodifiers like.font() - 🌗 Color theme syncs automatically with Dark Mode
Highlight is available as an environment value:
@Environment(\.highlight) var highlightAlternatively, create a new instance. By default the previous 50 highlights are cached. Use 0 to completely disable cacheing.
let highlight = Highlight(cacheLimit: 50)Convert a plain String of code into a syntax highlighted AttributedString:
let attributedText = try await highlight.attributed("print(\"Hello World\")")The language: parameter sets a specific language, disabling automatic detection.
let attributedText = try await highlight.attributed(code, language: "swift")The colors: parameter sets the highlight theme and the system color scheme:
let attributedText = try await highlight.attributed(code, colors: .dark(.solarFlare))The full request function provides the detected language and other details:
let result: HighlightResult = try await highlight.request("print(\"Hello World\")")
// HighlightResult(
// attributedText: "...",
// relevance: 5,
// language: "swift",
// languageName: "Swift?",
// backgroundColor: #1F2024FF,
// hasIllegal: false,
// isUndefined: false
// )Create a CodeText view:
CodeText("print(\"Hello World\")")Typical Text modifiers like .font() can be applied:
CodeText("print(\"Hello World\")")
.font(.system(.callout, weight: .semibold))The .codeTextTheme(_:) modifier sets one of the 30 built-in color themes.
Each theme has a dark color scheme variant that is used automatically in Dark Mode:
CodeText("print(\"Hello World\")")
.codeTextTheme(.github)The .codeTextLanguage(_:) modifier sets a specific language, disabling automatic detection:
CodeText("print(\"Hello World\")")
.codeTextLanguage(.swift)The optional result binding provides the detected language, background color and other details:
@Binding var result: HighlightResult?
var body: some View {
CodeText("print(\"Hello World\")", result: $result)
}- In Xcode, go to
File>Add packages... - Enter
https://github.com/appstefan/highlightswiftin 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.0.0")
],
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.