loopwerk/moon
A (Linux compatible) Swift library for server-side syntax highlighting using [Prism.js](https://prismjs.com/).
Features
- Server-side syntax highlighting for 290+ languages
- Process entire HTML documents
- Support for custom Prism.js bundles and plugins
- Cross-platform: macOS, iOS, and Linux
Installation
Add Moon to your Package.swift:
dependencies: [
.package(url: "https://github.com/loopwerk/Moon", from: "1.0.0"),
]Then add it to your target:
.target(
name: "YourTarget",
dependencies: ["Moon"]
)Usage
Basic Usage
import Moon
// Process an entire HTML document
let html = """
<pre><code class="language-python">def hello():
print("Hello, World!")
</code></pre>
"""
let highlighted = Moon.shared.highlightCodeBlocks(in: html)Additional Plugins
Moon includes a Prism.js bundle with all standard languages, and it preserves HTML markup within code blocks, like the Keep Markup plugin. For languages not included (like Svelte), you can load additional plugins:
let moon = try Moon(additionalPlugins: ["prism-svelte.js"])The plugin files must be included in your target's resources:
.target(
name: "YourTarget",
dependencies: ["Moon"],
resources: [
.copy("Resources/prism-svelte.js"),
]
)Custom Prism.js Bundle
To use a custom Prism.js bundle, create one at prismjs.com/download.html and save it as prism.js in your target's resources:
.target(
name: "YourTarget",
dependencies: ["Moon"],
resources: [
.copy("Resources/prism.js"),
]
)How It Works
Moon embeds Prism.js and executes it via JavaScriptCore (using JXKit). This provides 100% Prism.js compatibility with all its language definitions.
The highlightCodeBlocks(in:) method finds all <code class="language-xxx"> blocks in HTML and applies syntax highlighting, returning the modified HTML with Prism's token classes applied.
Output Format
Moon outputs HTML with Prism.js CSS classes:
<code class="language-python">
<span class="token keyword">def</span>
<span class="token function">hello</span>
<span class="token punctuation">(</span>
<span class="token punctuation">)</span>
<span class="token punctuation">:</span>
...
</code>Use any Prism.js theme to style the output.
Requirements
- Swift 5.10+
- macOS 14+ / iOS 17+ / Linux
On Linux, you need to install WebKit GTK development libraries:
$ sudo apt install libjavascriptcoregtk-4.1-dev
# Fedora
$ sudo dnf install webkit2gtk4.1-develLicense
Moon is available under the MIT license. See the LICENSE file for more info.
Prism.js is available under the MIT license. You can find the LICENSE file here.
Package Metadata
Repository: loopwerk/moon
Default branch: main
README: README.md