HighlightSwift

repository·main·Indexed 42 days ago

https://github.com/appstefan/highlightswift

A syntax highlighting library for Swift and SwiftUI that utilizes highlight.js and JavaScriptCore to convert code strings into highlighted AttributedString or SwiftUI views. It supports over 50 languages and 30 built-in themes, providing a Highlight class for text conversion and a CodeText SwiftUI view for displaying code with customizable styles and themes.

Tokens
1.4K
Snippets
4
Records
4
Agent score
3%

What's inside HighlightSwift

  1. Install HighlightSwift via Xcode or Swift Package Manager

    main

    You can integrate HighlightSwift into your project using either the Xcode GUI or by modifying your Package.swift file.

    Xcode (Project)

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

    Swift Package Manager (Package)

    Add the repository as a dependency in your Package.swift file:

    dependencies: [
        .package(url: "https://github.com/appstefan/highlightswift.git", from: "1.1")
    ],
    targets: [
        .target(
            name: "YourPackageName",
            dependencies: ["HighlightSwift"]
        )
    ]
  2. Persist HighlightResult to optimize SwiftUI List performance

    main

    To prevent re-calculating highlights when a view reappears (e.g., in a List), you can pass a previously stored HighlightResult directly into the CodeText initializer. Combine this with .onHighlightSuccess to cache the result in a @State variable.

    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
                }
        }
    }
  3. Use the Highlight class to convert code to AttributedString

    main

    The Highlight class provides a way to convert a raw String of code into a syntax-highlighted AttributedString. It supports automatic language detection, 50+ languages, and 30+ built-in themes.

    Basic Usage

    let someCode = """
        print("Hello World")
        """
    let highlight = Highlight()
    let attributedText = try await highlight.attributedText(someCode)

    Customizing Language and Themes

    • Set Language: Use the language: parameter to disable automatic detection and force a specific language.
    • Set Theme: Use the colors: parameter. You can use .dark(.themeName) or provide custom CSS via .custom(css: "...") following the highlight.js Theme Guide.

    Fetching Detailed Results

    Use .request() to get a HighlightResult object containing metadata like relevance score, detected language, and background color.

    // Basic conversion
    let highlight = Highlight()
    let attributedText = try await highlight.attributedText(someCode)
    
    // Forced language
    let attributedText = try await highlight.attributedText(someCode, language: "swift")
    
    // Custom theme
    let attributedText = try await highlight.attributedText(someCode, colors: .dark(.github))
    
    // Custom CSS
    let attributedText = try await highlight.attributedText(someCode, colors: .custom(css: someCSS))
    
    // Detailed metadata
    let result: HighlightResult = try await highlight.request(someCode)
  4. Display highlighted code with the CodeText SwiftUI view

    main

    The CodeText view is a SwiftUI component designed to display syntax-highlighted code. It uses a .monospaced font by default and automatically syncs themes with Dark Mode.

    Basic Implementation

    CodeText(someCode)

    Customizing CodeText

    • Language: Use .highlightLanguage(.language) to set a specific language and disable auto-detection.
    • Colors: Use .codeTextColors(.themeName) to apply a theme. For custom CSS, use .codeTextColors(.custom(dark: .custom(css: ...), light: .custom(css: ...))).
    • Styles: Use .codeTextStyle(.card) to add a background and padding. The .card style can be customized with cornerRadius, stroke, and verticalPadding.
    • Callbacks: Use .onHighlightSuccess, .onHighlightFailure, or the combined .onHighlightResult to handle the highlighting lifecycle.
    // Basic view
    CodeText(someCode)
        .font(.callout)
        .fontWeight(.semibold)
    
    // Set language
    CodeText(someCode)
        .highlightLanguage(.swift)
    
    // Set theme
    CodeText(someCode)
        .codeTextColors(.github)
    
    // Card style with customization
    CodeText(someCode)
        .codeTextStyle(.card(cornerRadius: 0, stroke: .separator, verticalPadding: 12))
    
    // Handling results
    CodeText(someCode)
        .onHighlightResult { result in
            switch result {
            case .success(let highlightResult):
                print(highlightResult.language)
            case .failure(let error):
                print(error)
            }
        }