Skip to content
프로젝트

소개

Code syntax highlighting in Swift and SwiftUI

개발 도구

이 수치를 측정하는 방법

측정된 스타 증가

in 24h
0
in 7 days
0
in 15 days
+1
in 1 month
기록 수집 중

서로 겹치는 기간의 순증가량이며 일별 합계가 아닙니다. 측정값이 없으면 비워 둡니다. 스타는 관심도를 나타내며 품질을 보장하지 않습니다.

README.md

Original

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(.theme(.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: .secondary, 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 CodeText view can reuse a previously stored result when the source, mode, and colors match. 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

Highlight supports iOS and tvOS 15 or later and macOS 13 or later. The SwiftUI CodeText view requires iOS or tvOS 16.1 or later, or macOS 13 or later.

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.0")
],
targets: [
    .target(
        name: "YourPackageName",
        dependencies: [.product(name: "HighlightSwift", package: "highlightswift")]
    )
]
Rebuilding the bundled highlight.js engine

From a checkout of highlight.js 11.12.0, run the following commands. The language list includes the existing string-only aliases as well as every HighlightLanguage case.

npm ci
node tools/build.js --target browser --no-esm \
  applescript arduino awk bash basic c clojure cpp csharp css dart delphi diff django \
  dockerfile elixir elm erlang fortran gherkin go gradle graphql haskell ini java \
  javascript json julia kotlin latex less lisp lua makefile markdown mathematica \
  matlab nix objectivec ocaml perl pgsql php php-template plaintext protobuf python \
  python-repl r ruby rust scala scss shell sql swift typescript vbnet wasm xml yaml

Copy build/highlight.min.js, LICENSE (as LICENSE.md), and NOTICE.txt into Sources/HighlightSwift/HighlightJS/, then run swift test in this package.

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.

관련 프로젝트 살펴보기

불러오는 중…