Skip to content

appstefan/HighlightSwift

Repository files navigation

HighlightSwift

Syntax Highlighting for Swift and SwiftUI

CodeCard

Contents

Highlight

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

CodeText

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

Highlight

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 with extra information:

let result: HighlightResult = try await highlight.request(someCode)
print(result)
HighlightResult(
    attributedText: "...",
    relevance: 5,
    language: "swift",
    languageName: "Swift?",
    backgroundColor: #1F2024FF,
    hasIllegal: false,
    isUndefined: false)

CodeText

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:

CodeText(someCode)
    .font(.callout)
    .fontWeight(.semibold)

Add the .highlightLanguage() modifier to set the language and disable automatic detection:

CodeText(someCode)
    .highlightLanguage(.swift)

Colors

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)))

Styles

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))

Results

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: 
                ...
        }
    }

A previously stored highlight result can be passed to the CodeText. In combination with .onHighlightSuccess() the result can be persisted 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
            }
        ...
    }
}

Installation

Project

  1. In Xcode, go to File > Add packages...
  2. Enter https://github.com/appstefan/highlightswift in the field and click Add Package

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"]
    )
]

Author

Stefan, [email protected]

License

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.