Swiftpack.co - Package - NSHipster/SwiftSyntaxHighlighter

SwiftSyntaxHighlighter

A syntax highlighter for Swift code that uses SwiftSyntax to generate Pygments-compatible HTML.

This functionality is discussed in the NSHipster article SwiftSyntax.

Requirements

  • Swift 4.2+

Installation

Swift Package Manager

Add the SwiftSyntaxHighlighter package to your target dependencies in Package.swift:

import PackageDescription

let package = Package(
  name: "YourProject",
  dependencies: [
    .package(
        url: "https://github.com/NSHipster/SwiftSyntaxHighlighter",
        from: "0.0.1"
    ),
  ]
)

Then run the swift build command to build your project.

Carthage

To use SwiftSyntaxHighlighter in your Xcode project using Carthage, specify it in Cartfile:

github "NSHipster/SwiftSyntaxHighlighter" ~> 0.0.1

Then run the carthage update command to build the framework, and drag the built SwiftSyntaxHighlighter.framework into your Xcode project.

Usage

SwiftSyntaxHighlighter provides two top-level functions named highlight(_:), with overloads for providing a file URL or passing source code directly as a String:

import SwiftSyntaxHighlighter

let code = """
print("Hello, world!")
"""

let html = highlight(code)

After running this code, html contains the following string:

<pre class="highlight"><code><span class="n">print</span><span class="p">(</span><span class="s2">"Hello, world!"</span><span class="p">)</span></code></pre>

This package also contains the Highlight executable target, which can be run from the command line. The command takes a single argument, which can be either a path to a source file or source code:

$ ./Highlight "print(\"Hello, world!\")"
<pre class="highlight"><code><span class="n">print</span><span class="p">(</span><span class="s2">"Hello, world!"</span><span class="p">)</span></code></pre>

Example Output

SwiftSyntaxHighlighter (0.0.1):

import Foundation

/*
 This is a multi-line comment block
 */
#if os(macOS)
class Class: NSObject {
    private static let message = """
        Hello, world!
    """
    @objc var storedProperty: Int = 0
    
    override init() {
        self.storedProperty = 0b10101010
        super.init()
    }
    
    func printSelectorAndKeyPath() {
        print(#selector(emptyFunction))
        print(#keyPath(storedProperty))
    }
    
    @objc func emptyFunction() { }
}
#endif

Standard highlighter output:

import Foundation

/*
 This is a multi-line comment block
 */
#if os(macOS)
class Class: NSObject {
    private static let message = """
        Hello, world!
    """
    @objc var storedProperty: Int = 0

    override init() {
        self.storedProperty = 0b10101010
        super.init()
    }

    func printSelectorAndKeyPath() {
        print(#selector(emptyFunction))
        print(#keyPath(storedProperty))
    }

    @objc func emptyFunction() { }
}
#endif

License

MIT

Contact

Mattt (@mattt)

Github

link
Stars: 170
Help us keep the lights on

Used By

Total: 0