SwiftSyntaxHighlighter

CI Documentation

一个使用 SwiftSyntax 的 Swift 代码语法高亮器。 你可以通过命令行使用 swift-highlight 可执行文件,或者在 Swift 代码中使用 SwiftSyntaxHighlighter 模块。

NSHipster 的 SwiftSyntax 文章讨论了此功能。

要求

命令行用法

可以从命令行运行 swift-highlight 可执行文件,以高亮显示源文件的路径或源代码

$ swift highlight 'print("Hello, world!")'
<pre class="highlight"><code><span class="keyword">let</span> <span class="variable">greeting</span> = <span class="string literal">&quot;</span><span class="string literal">Hello, world!</span><span class="string literal">&quot;</span></code></pre>

传递 --scheme pygments 选项以生成与 Pygments 兼容的 HTML

$ swift highlight 'print("Hello, world!")' --scheme pygments
<pre class="highlight"><code><span class="n">print</span><span class="p">(</span><span class="p">&quot;</span><span class="s2">Hello, world!</span><span class="p">&quot;</span><span class="p">)</span></code></pre>

swift-highlight 也接受从标准输入 (stdin) 管道传递的参数

echo 'print("Hello, world!")' | swift highlight
<pre class="highlight"><code><span class="variable">print</span>(<span class="string literal">&quot;</span><span class="string literal">Hello, world!</span><span class="string literal">&quot;</span>)
</code></pre>

安装

Homebrew

运行以下命令以使用 homebrew 安装

$ brew install nshipster/formulae/swift-syntax-highlight

手动

运行以下命令以手动构建和安装

$ git clone https://github.com/NSHipster/SwiftSyntaxHighlighter.git
$ cd SwiftSyntaxHighlighter
$ make install

代码用法

SwiftSyntaxHighlighter 提供了名为 highlight 的类型方法,可以接受源代码(String 类型)、源文件 URL 或由 SwiftSyntax 创建的 SourceFileSyntax AST。

import SwiftSyntaxHighlighter

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

let html = try SwiftSyntaxHighlighter.highlight(source: source, using: Xcode.self)

运行此代码后,html 包含以下字符串

<pre class="highlight"><code><span class="keyword">let</span> <span class="variable">greeting</span> = <span class="string literal">&quot;</span><span class="string literal">Hello, world!</span><span class="string literal">&quot;</span></code></pre>

安装

Swift 包管理器

将 SwiftSyntaxHighlighter 包添加到你的 Package.swift 文件中的目标依赖项中

import PackageDescription

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

然后运行 swift build 命令来构建你的项目。

已知问题

许可证

MIT

联系方式

Mattt (@mattt)