Markin

SwiftPM compatible license language Swift 5.1 platform iOS macOS tvOS

Markin 是一个用于解析类似 Markdown 文本格式的 Swift 库。

该库体积小,支持 Swift Package Manager,并且没有任何第三方依赖。

解析器生成一个元素树。该树符合 Codable 协议。

该树还可以转换回 Markin 格式。这意味着 Markin 文档可以被解析,通过修改/删除/替换/添加树元素以编程方式进行操作,并写回文件。

该库内置了 HTML 渲染,但完全可以对元素树进行外部渲染。

许可证

Markin 遵循 MIT 许可证。 有关详细信息,请参阅存储库中的 LICENSE 文件。

用法

添加 Markin 作为依赖项

在你的 Swift Package Manager 包的 Package.swift 文件中添加 Markin 包作为依赖项。 以下示例指定了对 master 分支上 Markin 包最新版本的依赖项。 您可能需要使用发布版本中的版本标签代替。

.package(url: "https://github.com/apparata/Markin.git", .branch("master"))

解析

只需实例化一个解析器,并使用 Markin 格式的字符串作为参数调用 parse() 方法。 parse() 方法返回一个 DocumentElement 对象,它是元素树的根对象。

let exampleMarkin = """
# This is a Header

This is a paragraph.
"""

do {
    let parser = MarkinParser()
    let document = try parser.parse(exampleMarkin)
} catch {
    print(error)
}

从元素树渲染 HTML

let document = try parser.parse(exampleMarkin)
let html = document.formatAsHTML()

从元素树转换回 Markin

let document = try parser.parse(exampleMarkin)
let markin = document.formatAsMarkin()

元素树转换为 JSON

let document = try parser.parse(exampleMarkin)
let jsonData = try JSONEncoder().encode(document)

JSON 转换为元素树

let document = try JSONDecoder().decode(DocumentElement.self, from: jsonData)

Markin 格式

该格式基于 Markdown,但我计划对其进行扩展。 然而,核心语法将保持不变。

标题

标题有 6 个层级可用

# This is the largest header
## This is the second largest header
### This is the third largest header
#### This is the fourth largest header
##### This is the fifth largest header
####### This is the sixth largest header.

目录

目录的占位符应该单独写在一行,如下所示

%TOC

文本段落

文本段落由连续的文本行组成,以空行终止。

This is the first sentence of the paragraph. This is the second sentence.
This is the third sentence, also in the paragraph.

This is a second paragraph.

块引用

块引用格式与文本段落相同,但每行都以 > 为前缀,如下所示

> This is the first line of the block quote.
> This is the second line of the block quote.
>
> This is the first line of the second paragraph
> of the block quote.

列表

无序列表

- First list entry
- Second list entry
    - First nested list entry
    - Second nested list entry
- Third list entry

有序列表

1. First list entry
1. Second list entry
    1. First nested list entry
    1. Second nested list entry
1. Third list entry

水平线

水平分隔线写成三个短划线,单独一行

---

代码块

代码可以写在代码块中。可以在开头 ``` 序列之后指定语言。

```Swift
let a = 7
```

粗体文本

粗体文本通过使用标记 * 来实现,如下所示

The word *bold* is bold in this sentence.

目前,粗体和斜体文本不能嵌套。

斜体文本

斜体文本通过使用标记 _ 来实现,如下所示

The word _italic_ is in italics in this sentence.

目前,粗体斜体 文本不能嵌套。

行内代码

可以使用单个反引号 ` 编写行内代码,像这样

This is text that has `inline code` in it.

链接

链接可以写成 [标题](url) 的形式,像这样

This is text that has a [link](https://google.com) in it.

图片

图片可以写成 ![标题](url) 的形式,像这样

This is text that has an image ![with alt text](mypicture.jpg) in it.

元素的继承树

实验性 SwiftUI 渲染器

你可以通过将 MarkinView 添加到你的视图中来尝试实验性的 SwiftUI 渲染器。

struct ContentView: View {
    
    let document: DocumentElement
    
    var body: some View {
        MarkinView(document: document)
    }
}