A syntax highlighter for Swift code that uses
SwiftSyntax.
You can use it either from the command-line,
via the swift-highlight
executable,
or in Swift code using the SwiftSyntaxHighlighter
module.
This functionality is discussed in the NSHipster article SwiftSyntax.
- Swift 5.3+
The swift-highlight
executable can be run from the command line
to highlight either a path to a source file or source code:
$ swift highlight 'print("Hello, world!")'
<pre class="highlight"><code><span class="keyword">let</span> <span class="variable">greeting</span> = <span class="string literal">"</span><span class="string literal">Hello, world!</span><span class="string literal">"</span></code></pre>
Pass the --scheme pygments
option
to generate Pygments-compatible HTML:
$ swift highlight 'print("Hello, world!")' --scheme pygments
<pre class="highlight"><code><span class="n">print</span><span class="p">(</span><span class="p">"</span><span class="s2">Hello, world!</span><span class="p">"</span><span class="p">)</span></code></pre>
swift-highlight
also accepts arguments piped from standard input (stdin
):
echo 'print("Hello, world!")' | swift highlight
<pre class="highlight"><code><span class="variable">print</span>(<span class="string literal">"</span><span class="string literal">Hello, world!</span><span class="string literal">"</span>)
</code></pre>
Run the following command to install using homebrew:
$ brew install nshipster/formulae/swift-syntax-highlight
Run the following commands to build and install manually:
$ git clone https://github.com/NSHipster/SwiftSyntaxHighlighter.git
$ cd SwiftSyntaxHighlighter
$ make install
SwiftSyntaxHighlighter
provides type methods named highlight
that take either
source code as a String
,
a source file URL
,
or a SourceFileSyntax
AST created by SwiftSyntax.
import SwiftSyntaxHighlighter
let code = """
print("Hello, world!")
"""
let html = try SwiftSyntaxHighlighter.highlight(source: source, using: Xcode.self)
After running this code,
html
contains the following string:
<pre class="highlight"><code><span class="keyword">let</span> <span class="variable">greeting</span> = <span class="string literal">"</span><span class="string literal">Hello, world!</span><span class="string literal">"</span></code></pre>
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: "1.2.0"
),
]
)
Then run the swift build
command to build your project.
To use SwiftSyntaxHighlighter
in your Xcode project using Carthage,
specify it in Cartfile
:
github "NSHipster/SwiftSyntaxHighlighter" ~> 1.2.0
Then run the carthage update
command to build the framework,
and drag the built SwiftSyntaxHighlighter.framework into your Xcode project.
MIT
Mattt (@mattt)