CommonMarkAttributedString

CI Documentation

CommonMarkAttributedString 是一个 Swift 包,它允许你使用熟悉的 CommonMark (Markdown) 语法来创建富文本字符串。它构建于 CommonMark 之上,完全符合 CommonMark Spec

支持的平台

用法

import CommonMarkAttributedString

let commonmark = "A *bold* way to add __emphasis__ to your `code`"

let attributes: [NSAttributedString.Key: Any] = [
    .font: NSFont.systemFont(ofSize: 24.0),
    .foregroundColor: NSColor.systemBlue,
]

let attributedString = try NSAttributedString(commonmark: commonmark, attributes: attributes)

Result

你也可以使用 CommonMarkAttributedString 来创建包含多个段落、链接、标题、列表和图像的富文本字符串。

let commonmark = #"""
# [Universal Declaration of Human Rights][uhdr]

## Article 1.

All human beings are born free and equal in dignity and rights.
They are endowed with reason and conscience
and should act towards one another in a spirit of brotherhood.

[uhdr]: https://www.un.org/en/universal-declaration-human-rights/ "View full version"
"""#

let attributes: [NSAttributedString.Key: Any] = [
    .font: NSFont.systemFont(ofSize: NSFont.systemFontSize),
    .foregroundColor: NSColor.textColor,
    .backgroundColor: NSColor.textBackgroundColor,
]

let attributedString = try NSAttributedString(commonmark: commonmark, attributes: attributes)

Result

支持的 CommonMark 元素

原始内联 HTML

根据 CommonMark 规范,每个内联 HTML 标签都被视为它自己的元素。也就是说,CommonMark 没有开始或结束标签的概念。因此,例如,CommonMark 字符串 <span style="color: red;">hello</span> 对应于一个段落块,其中包含三个内联元素

解析和渲染 HTML 超出了此库的范围,因此每当 CommonMarkAttributedString 接收到包含任何 HTML 的文本时,它会回退到 NSAttributedString 的内置 HTML 初始化器。

无序列表和有序列表

CommonMarkAttributedString 使用传统的缩进和标记渲染无序列表和有序列表 --- 无序列表使用圆点 (•)、圆圈 (◦) 和方块 (■),有序列表使用十进制数字 (1.)、小写罗马数字 (i.) 和小写字母 (a.)。


  1. 层级 1
    1. 层级 2
      1. 层级 3

图片

富文本字符串可以使用 NSTextAttachment 类嵌入图像。但是,没有内置的方法可以异步加载图像。CommonMarkAttributedString 提供了一个可选的 attachments 参数,你可以使用它将现有文本附件与图像 URL 字符串关联,而不是在 CommonMark 文本中遇到图像时同步加载它们。

let commonmark = "![](https://example.com/image.png)"

let attachments: [String: NSTextAttachment] = [
    "https://example.com/image.png": NSTextAttachment(data: <#...#>, ofType: "public.png")
]

let attributedString = try NSAttributedString(commonmark: commonmark, attributes: attributes, attachments: attachments)

要求

安装

Swift Package Manager

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

import PackageDescription

let package = Package(
  name: "YourProject",
  dependencies: [
    .package(
        url: "https://github.com/mattt/CommonMarkAttributedString",
        from: "0.2.0"
    ),
  ]
)

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

许可证

MIT

联系方式

Mattt (@mattt)