Skip to content
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 4 additions & 11 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,14 @@ on:
- main
pull_request:
jobs:
xenial:
test:
container:
image: vapor/swift:5.2-xenial
image: swift:6.3
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- run: swift test --enable-test-discovery --enable-code-coverage
bionic:
container:
image: vapor/swift:5.2-bionic
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v7
- name: Run Bionic Tests
run: swift test --enable-test-discovery --enable-code-coverage
run: swift test
- name: Setup container for codecov upload
run: apt-get update && apt-get install -y curl
- name: Process coverage file
Expand Down
42 changes: 31 additions & 11 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1,19 @@
// swift-tools-version:5.2
// swift-tools-version:6.1

import PackageDescription

let extraSettings: [SwiftSetting] = [
.enableExperimentalFeature("SuppressedAssociatedTypesWithDefaults"),
.enableExperimentalFeature("LifetimeDependence"),
.enableExperimentalFeature("Lifetimes"),
.enableUpcomingFeature("LifetimeDependence"),
.enableUpcomingFeature("NonisolatedNonsendingByDefault"),
.enableUpcomingFeature("InferIsolatedConformances"),
.enableUpcomingFeature("ExistentialAny"),
.enableUpcomingFeature("MemberImportVisibility"),
.enableUpcomingFeature("InternalImportsByDefault"),
]

let package = Package(
name: "LeafMarkdown",
platforms: [
Expand All @@ -11,17 +23,25 @@ let package = Package(
.library(name: "LeafMarkdown", targets: ["LeafMarkdown"]),
],
dependencies: [
.package(name: "SwiftMarkdown", url: "https://github.com/vapor-community/markdown.git", from: "0.6.1"),
.package(url: "https://github.com/vapor/leaf-kit.git", from: "1.3.1"),
.package(url: "https://github.com/swiftlang/swift-cmark.git", from: "0.8.0"),
.package(url: "https://github.com/vapor/leaf-kit.git", from: "1.14.3"),
],
targets: [
.target(name: "LeafMarkdown", dependencies: [
.product(name: "LeafKit", package: "leaf-kit"),
.product(name: "SwiftMarkdown", package: "SwiftMarkdown"),
]),
.testTarget(name: "LeafMarkdownTests", dependencies: [
.target(name: "LeafMarkdown"),
.product(name: "LeafKit", package: "leaf-kit"),
]),
.target(
name: "LeafMarkdown",
dependencies: [
.product(name: "LeafKit", package: "leaf-kit"),
.product(name: "cmark-gfm", package: "swift-cmark"),
.product(name: "cmark-gfm-extensions", package: "swift-cmark"),
],
swiftSettings: extraSettings
),
.testTarget(
name: "LeafMarkdownTests",
dependencies: [
.target(name: "LeafMarkdown"),
.product(name: "LeafKit", package: "leaf-kit"),
],
swiftSettings: extraSettings),
]
)
59 changes: 54 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
# Leaf Markdown

[![Language](https://img.shields.io/badge/Swift-5.2-brightgreen.svg)](http://swift.org)
[![Language](https://img.shields.io/badge/Swift-6.1-brightgreen.svg)](http://swift.org)
[![Build Status](https://github.com/vapor-community/leaf-markdown/workflows/CI/badge.svg?branch=main)](https://github.com/vapor-community/leaf-markdown/actions)
[![codecov](https://codecov.io/gh/vapor-community/leaf-markdown/branch/main/graph/badge.svg)](https://codecov.io/gh/vapor-community/leaf-markdown)
[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/vapor-community/leaf-markdown/main/LICENSE)

A Markdown renderer for Vapor and Leaf. This uses the [Vapor Markdown](https://github.com/vapor/markdown) package to wrap [cmark](https://github.com/github/cmark-gfm) (though a [fork](https://github.com/brokenhandsio/cmark-gfm) is used to make it work with Swift PM), so it understands [Common Mark](http://commonmark.org). A quick reference guide for Common Mark can be found [here](http://commonmark.org/help/). It also supports [Github Flavored Markdown](https://guides.github.com/features/mastering-markdown/).
A Markdown renderer for Vapor and Leaf. This wraps [swift-cmark](https://github.com/swiftlang/swift-cmark), the Swift project's fork of [cmark-gfm](https://github.com/github/cmark-gfm), so it understands [CommonMark](http://commonmark.org). A quick reference guide for CommonMark can be found [here](http://commonmark.org/help/). It also supports [GitHub Flavored Markdown](https://guides.github.com/features/mastering-markdown/) — tables, strikethrough, task lists and autolinks are all enabled.

## Usage

Expand All @@ -32,7 +32,7 @@ Add Leaf Markdown as a dependency in your `Package.swift` file:
```swift
dependencies: [
...,
.package(name: "LeafMarkdown", url: "https://github.com/vapor-community/leaf-markdown.git", .upToNextMajor(from: "3.0.0")),
.package(url: "https://github.com/vapor-community/leaf-markdown.git", .upToNextMajor(from: "4.0.0")),
]
```

Expand All @@ -43,7 +43,7 @@ Then add the dependency to your target:
name: "App",
dependencies: [
// ...
"LeafMarkdown"
.product(name: "LeafMarkdown", package: "leaf-markdown"),
],
// ...
)
Expand All @@ -54,7 +54,56 @@ Then add the dependency to your target:
Register the tag with Leaf so Leaf knows about it:

```swift
app.leaf.tags["markdown"] = Markdown()
app.leaf.tags["markdown"] = MarkdownTag()
```

Don't forget to import LeafMarkdown in the file you register the tag with `import LeafMarkdown`.

## Options

`MarkdownTag` accepts a `MarkdownOptions` set to control how markdown is parsed and rendered:

```swift
app.leaf.tags["markdown"] = MarkdownTag(options: [.smart, .footnotes])
```

### Rendering

| Option | Effect |
| --- | --- |
| `.unsafe` | Render raw HTML and unsafe links instead of stripping them. See the warning below. |
| `.sourcePos` | Include a `data-sourcepos` attribute on all block elements. |
| `.hardBreaks` | Render soft breaks as hard line breaks. |
| `.noBreaks` | Render soft breaks as spaces. |
| `.githubPreLang` | Use GitHub-style `<pre lang="x">` for code blocks instead of `<pre><code class="language-x">`. |
| `.tablePreferStyleAttributes` | Align table cells with `style` attributes instead of `align` attributes. |

### Parsing

| Option | Effect |
| --- | --- |
| `.smart` | Convert straight quotes to curly, `---` to em dashes and `--` to en dashes. |
| `.footnotes` | Parse footnotes. |
| `.validateUTF8` | Replace illegal UTF-8 sequences with U+FFFD before parsing. |
| `.liberalHTMLTag` | Be liberal in interpreting inline HTML tags. |
| `.strikethroughDoubleTilde` | Only parse strikethroughs surrounded by exactly two tildes. |
| `.fullInfoString` | Include a code block's full info string in a `data-meta` attribute. |

## Rendering untrusted markdown

By default, raw HTML in the markdown source is replaced with an `<!-- raw HTML omitted -->` comment, and links using `javascript:`, `vbscript:`, `file:` and most `data:` schemes are replaced with an empty destination. Text and attribute values are escaped.

```swift
// "<br>" -> "<!-- raw HTML omitted -->"
// "[click](javascript:x())" -> "<a href=\"\">click</a>"
MarkdownTag()
```

Passing `.unsafe` turns all of that off:

```swift
// "<br>" -> "<br>"
MarkdownTag(options: [.unsafe])
```

Only use `.unsafe` for markdown you control. If you are rendering markdown submitted by your users, leave it off.
57 changes: 57 additions & 0 deletions Sources/LeafMarkdown/MarkdownOptions.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import cmark_gfm

/// Options controlling how markdown is parsed and rendered to HTML.
///
/// These map directly onto the underlying cmark-gfm options.
public struct MarkdownOptions: OptionSet, Sendable {
public var rawValue: Int32

public init(rawValue: Int32) {
self.rawValue = rawValue
}

// MARK: - Rendering

/// Render raw HTML and unsafe links (`javascript:`, `vbscript:`, `file:` and most
/// `data:` URLs) instead of stripping them.
///
/// By default cmark replaces raw HTML with an HTML comment and unsafe links with an
/// empty string. Only enable this for markdown you trust.
public static let unsafe = MarkdownOptions(rawValue: CMARK_OPT_UNSAFE)

/// Include a `data-sourcepos` attribute on all block elements.
public static let sourcePos = MarkdownOptions(rawValue: CMARK_OPT_SOURCEPOS)

/// Render soft break elements as hard line breaks.
public static let hardBreaks = MarkdownOptions(rawValue: CMARK_OPT_HARDBREAKS)

/// Render soft break elements as spaces.
public static let noBreaks = MarkdownOptions(rawValue: CMARK_OPT_NOBREAKS)

/// Use GitHub-style `<pre lang="x">` tags for code blocks instead of
/// `<pre><code class="language-x">`.
public static let githubPreLang = MarkdownOptions(rawValue: CMARK_OPT_GITHUB_PRE_LANG)

/// Use `style` attributes to align table cells instead of `align` attributes.
public static let tablePreferStyleAttributes = MarkdownOptions(rawValue: CMARK_OPT_TABLE_PREFER_STYLE_ATTRIBUTES)

// MARK: - Parsing

/// Validate UTF-8 in the input before parsing, replacing illegal sequences with U+FFFD.
public static let validateUTF8 = MarkdownOptions(rawValue: CMARK_OPT_VALIDATE_UTF8)

/// Convert straight quotes to curly, `---` to em dashes and `--` to en dashes.
public static let smart = MarkdownOptions(rawValue: CMARK_OPT_SMART)

/// Be liberal in interpreting inline HTML tags.
public static let liberalHTMLTag = MarkdownOptions(rawValue: CMARK_OPT_LIBERAL_HTML_TAG)

/// Parse footnotes.
public static let footnotes = MarkdownOptions(rawValue: CMARK_OPT_FOOTNOTES)

/// Only parse strikethroughs if surrounded by exactly two tildes.
public static let strikethroughDoubleTilde = MarkdownOptions(rawValue: CMARK_OPT_STRIKETHROUGH_DOUBLE_TILDE)

/// Include the full info string of a code block in the `data-meta` attribute.
public static let fullInfoString = MarkdownOptions(rawValue: CMARK_OPT_FULL_INFO_STRING)
}
60 changes: 45 additions & 15 deletions Sources/LeafMarkdown/Tag.swift
Original file line number Diff line number Diff line change
@@ -1,34 +1,64 @@
import LeafKit
import SwiftMarkdown
public import LeafKit
import Foundation
import cmark_gfm
import cmark_gfm_extensions

public struct Markdown: UnsafeUnescapedLeafTag {
public struct MarkdownTag: UnsafeUnescapedLeafTag {
public enum Error: Swift.Error {
case invalidArgument(LeafData?)
case parsingFailed
case renderingFailed
}

private let options: MarkdownOptions?

public init(options: MarkdownOptions? = nil) {

/// The GitHub Flavored Markdown extensions attached to the parser.
private static let extensionNames = ["table", "strikethrough", "tasklist", "autolink", "tagfilter"]

private let options: MarkdownOptions

public init(options: MarkdownOptions = []) {
self.options = options
}

public func render(_ ctx: LeafContext) throws -> LeafData {
var markdown = ""

if let markdownArgument = ctx.parameters.first, !markdownArgument.isNil {
guard let markdownArgumentValue = markdownArgument.string else {
throw Error.invalidArgument(ctx.parameters.first)
}
markdown = markdownArgumentValue
}

let markdownHTML: String
if let options = options {
markdownHTML = try markdownToHTML(markdown, options: options)
} else {
markdownHTML = try markdownToHTML(markdown)
return .string(try Self.markdownToHTML(markdown, options: options))
}

static func markdownToHTML(_ markdown: String, options: MarkdownOptions) throws -> String {
cmark_gfm_core_extensions_ensure_registered()

guard let parser = cmark_parser_new(options.rawValue) else {
throw Error.parsingFailed
}
defer { cmark_parser_free(parser) }

for name in Self.extensionNames {
if let syntaxExtension = cmark_find_syntax_extension(name) {
cmark_parser_attach_syntax_extension(parser, syntaxExtension)
}
}

cmark_parser_feed(parser, markdown, markdown.utf8.count)

guard let document = cmark_parser_finish(parser) else {
throw Error.parsingFailed
}
defer { cmark_node_free(document) }

// The extension list is owned by the parser, so this must happen before it is freed.
guard let html = cmark_render_html(document, options.rawValue, cmark_parser_get_syntax_extensions(parser)) else {
throw Error.renderingFailed
}
defer { free(html) }

return .string(markdownHTML)
return String(cString: html)
}
}
Loading
Loading