Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
2 changes: 0 additions & 2 deletions .gitattributes

This file was deleted.

12 changes: 5 additions & 7 deletions .github/workflows/format.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,13 @@ on:
jobs:
format:
name: swift-format
runs-on: macos-12
runs-on: macos-13
steps:
- uses: actions/checkout@v2
- name: Select Xcode 14.2
run: sudo xcode-select -s /Applications/Xcode_14.2.app
- name: Tap
run: brew tap pointfreeco/formulae
- uses: actions/checkout@v4
- name: Select Xcode
run: sudo xcode-select -s /Applications/Xcode_15.0.app
- name: Install
run: brew install Formulae/swift-format@5.7
run: brew install swift-format
- name: Format
run: make format
- uses: stefanzweifel/git-auto-commit-action@v4
Expand Down
90 changes: 89 additions & 1 deletion Examples/Demo/Demo/CodeSyntaxHighlightView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ struct CodeSyntaxHighlightView: View {
}

func highlightCode(_ content: String, language: String?) -> Text {
guard language?.lowercased() == "swift" else {
guard language != nil else {
return Text(content)
}

Expand All @@ -50,15 +50,92 @@ struct CodeSyntaxHighlightView: View {
.markdownCodeSyntaxHighlighter(.splash(theme: .sunset(withFont: .init(size: 16))))
}
```

More languages to render:

```
A plain code block without the specifying a language name.
```

```cpp
#include <iostream>
#include <vector>

int main() {
std::vector<std::string> fruits = {"apple", "banana", "orange"};
for (const std::string& fruit : fruits) {
std::cout << "I love " << fruit << "s!" << std::endl;
}
return 0;
}
```

```typescript
interface Person {
name: string;
age: number;
}

const person = Person();
```

```ruby
fruits = ["apple", "banana", "orange"]
fruits.each do |fruit|
puts "I love #{fruit}s!"
end
```

"""#

var body: some View {
DemoView {
Markdown(self.content)
.markdownBlockStyle(\.codeBlock) {
codeBlock($0)
}
.markdownCodeSyntaxHighlighter(.splash(theme: self.theme))
}
}

@ViewBuilder
private func codeBlock(_ configuration: CodeBlockConfiguration) -> some View {
VStack(spacing: 0) {
HStack {
Text(configuration.language ?? "plain text")
.font(.system(.caption, design: .monospaced))
.fontWeight(.semibold)
.foregroundColor(Color(theme.plainTextColor))
Spacer()

Image(systemName: "clipboard")
.onTapGesture {
copyToClipboard(configuration.content)
}
}
.padding(.horizontal)
.padding(.vertical, 8)
.background {
Color(theme.backgroundColor)
}

Divider()

ScrollView(.horizontal) {
configuration.label
.relativeLineSpacing(.em(0.25))
.markdownTextStyle {
FontFamilyVariant(.monospaced)
FontSize(.em(0.85))
}
.padding()
}
}
.background(Color(.secondarySystemBackground))
.clipShape(RoundedRectangle(cornerRadius: 8))
.markdownMargin(top: .zero, bottom: .em(0.8))
}

private var theme: Splash.Theme {
// NOTE: We are ignoring the Splash theme font
switch self.colorScheme {
Expand All @@ -68,6 +145,17 @@ struct CodeSyntaxHighlightView: View {
return .sunset(withFont: .init(size: 16))
}
}

private func copyToClipboard(_ string: String) {
#if os(macOS)
if let pasteboard = NSPasteboard.general {
pasteboard.clearContents()
pasteboard.setString(string, forType: .string)
}
#elseif os(iOS)
UIPasteboard.general.string = string
#endif
}
}

struct CodeSyntaxHighlightView_Previews: PreviewProvider {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ struct SplashCodeSyntaxHighlighter: CodeSyntaxHighlighter {
}

func highlightCode(_ content: String, language: String?) -> Text {
guard language?.lowercased() == "swift" else {
guard language != nil else {
return Text(content)
}

Expand Down
9 changes: 9 additions & 0 deletions Package.resolved

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,14 @@ let package = Package(
dependencies: [
.package(url: "https://github.com/gonzalezreal/NetworkImage", from: "6.0.0"),
.package(url: "https://github.com/pointfreeco/swift-snapshot-testing", from: "1.10.0"),
.package(url: "https://github.com/swiftlang/swift-cmark", from: "0.4.0"),
],
targets: [
.target(name: "cmark-gfm"),
.target(
name: "MarkdownUI",
dependencies: [
"cmark-gfm",
.product(name: "cmark-gfm", package: "swift-cmark"),
.product(name: "cmark-gfm-extensions", package: "swift-cmark"),
.product(name: "NetworkImage", package: "NetworkImage"),
]
),
Expand Down
2 changes: 1 addition & 1 deletion Sources/MarkdownUI/DSL/Inlines/InlineContentBuilder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import Foundation
/// A result builder that you can use to compose Markdown inline content.
///
/// You don't call the methods of the result builder directly. Instead, MarkdownUI annotates the `content` parameter of the
/// ``Paragraph``, ``Heading``, and ``TextTableColumn`` initializers with the `@InlineContentBuider` attribute,
/// ``Paragraph``, ``Heading``, and ``TextTableColumn`` initializers with the `@InlineContentBuilder` attribute,
/// implicitly calling this builder for you.
@resultBuilder public enum InlineContentBuilder {
public static func buildBlock(_ components: InlineContentProtocol...) -> InlineContent {
Expand Down
10 changes: 10 additions & 0 deletions Sources/MarkdownUI/DSL/Inlines/SoftBreak.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,13 @@ public struct SoftBreak: InlineContentProtocol {
.init(inlines: [.softBreak])
}
}

extension SoftBreak {
public enum Mode {
/// Treat a soft break as a space
case space

/// Treat a soft break as a line break
case lineBreak
}
}
2 changes: 1 addition & 1 deletion Sources/MarkdownUI/Parser/InlineNode.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Foundation

enum InlineNode: Hashable {
enum InlineNode: Hashable, Sendable {
case text(String)
case softBreak
case lineBreak
Expand Down
41 changes: 37 additions & 4 deletions Sources/MarkdownUI/Parser/MarkdownParser.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Foundation
@_implementationOnly import cmark_gfm
@_implementationOnly import cmark_gfm_extensions

extension Array where Element == BlockNode {
init(markdown: String) {
Expand Down Expand Up @@ -317,7 +318,7 @@ extension UnsafeNode {
return node
case .table(let columnAlignments, let rows):
guard let table = cmark_find_syntax_extension("table"),
let node = cmark_node_new_with_ext(CMARK_NODE_TABLE, table)
let node = cmark_node_new_with_ext(ExtensionNodeTypes.shared.CMARK_NODE_TABLE, table)
else {
return nil
}
Expand Down Expand Up @@ -354,7 +355,7 @@ extension UnsafeNode {

fileprivate static func make(_ tableRow: RawTableRow) -> UnsafeNode? {
guard let table = cmark_find_syntax_extension("table"),
let node = cmark_node_new_with_ext(CMARK_NODE_TABLE_ROW, table)
let node = cmark_node_new_with_ext(ExtensionNodeTypes.shared.CMARK_NODE_TABLE_ROW, table)
else {
return nil
}
Expand All @@ -364,7 +365,7 @@ extension UnsafeNode {

fileprivate static func make(_ tableCell: RawTableCell) -> UnsafeNode? {
guard let table = cmark_find_syntax_extension("table"),
let node = cmark_node_new_with_ext(CMARK_NODE_TABLE_CELL, table)
let node = cmark_node_new_with_ext(ExtensionNodeTypes.shared.CMARK_NODE_TABLE_CELL, table)
else {
return nil
}
Expand Down Expand Up @@ -400,7 +401,8 @@ extension UnsafeNode {
return node
case .strikethrough(let children):
guard let strikethrough = cmark_find_syntax_extension("strikethrough"),
let node = cmark_node_new_with_ext(CMARK_NODE_STRIKETHROUGH, strikethrough)
let node = cmark_node_new_with_ext(
ExtensionNodeTypes.shared.CMARK_NODE_STRIKETHROUGH, strikethrough)
else {
return nil
}
Expand Down Expand Up @@ -480,3 +482,34 @@ private struct UnsafeNodeSequence: Sequence {
.init(self.node)
}
}

// Extension node types are not exported in `cmark_gfm_extensions`,
// so we need to look for them in the symbol table
private struct ExtensionNodeTypes {
let CMARK_NODE_TABLE: cmark_node_type
let CMARK_NODE_TABLE_ROW: cmark_node_type
let CMARK_NODE_TABLE_CELL: cmark_node_type
let CMARK_NODE_STRIKETHROUGH: cmark_node_type

static let shared = ExtensionNodeTypes()

private init() {
func findNodeType(_ name: String, in handle: UnsafeMutableRawPointer!) -> cmark_node_type? {
guard let symbol = dlsym(handle, name) else {
return nil
}
return symbol.assumingMemoryBound(to: cmark_node_type.self).pointee
}

let handle = dlopen(nil, RTLD_LAZY)

self.CMARK_NODE_TABLE = findNodeType("CMARK_NODE_TABLE", in: handle) ?? CMARK_NODE_NONE
self.CMARK_NODE_TABLE_ROW = findNodeType("CMARK_NODE_TABLE_ROW", in: handle) ?? CMARK_NODE_NONE
self.CMARK_NODE_TABLE_CELL =
findNodeType("CMARK_NODE_TABLE_CELL", in: handle) ?? CMARK_NODE_NONE
self.CMARK_NODE_STRIKETHROUGH =
findNodeType("CMARK_NODE_STRIKETHROUGH", in: handle) ?? CMARK_NODE_NONE

dlclose(handle)
}
}
18 changes: 15 additions & 3 deletions Sources/MarkdownUI/Renderer/AttributedStringInlineRenderer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@ extension InlineNode {
func renderAttributedString(
baseURL: URL?,
textStyles: InlineTextStyles,
softBreakMode: SoftBreak.Mode,
attributes: AttributeContainer
) -> AttributedString {
var renderer = AttributedStringInlineRenderer(
baseURL: baseURL,
textStyles: textStyles,
softBreakMode: softBreakMode,
attributes: attributes
)
renderer.render(self)
Expand All @@ -21,12 +23,19 @@ private struct AttributedStringInlineRenderer {

private let baseURL: URL?
private let textStyles: InlineTextStyles
private let softBreakMode: SoftBreak.Mode
private var attributes: AttributeContainer
private var shouldSkipNextWhitespace = false

init(baseURL: URL?, textStyles: InlineTextStyles, attributes: AttributeContainer) {
init(
baseURL: URL?,
textStyles: InlineTextStyles,
softBreakMode: SoftBreak.Mode,
attributes: AttributeContainer
) {
self.baseURL = baseURL
self.textStyles = textStyles
self.softBreakMode = softBreakMode
self.attributes = attributes
}

Expand Down Expand Up @@ -67,10 +76,13 @@ private struct AttributedStringInlineRenderer {
}

private mutating func renderSoftBreak() {
if self.shouldSkipNextWhitespace {
switch softBreakMode {
case .space where self.shouldSkipNextWhitespace:
self.shouldSkipNextWhitespace = false
} else {
case .space:
self.result += .init(" ", attributes: self.attributes)
case .lineBreak:
self.renderLineBreak()
}
}

Expand Down
Loading
Loading