Skip to content
Open
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
22 changes: 22 additions & 0 deletions CDMarkdownKitTests/TestSyntax.swift
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,28 @@ final class TestSyntax: XCTestCase {
XCTAssertFalse(TestHelpers.isMonospaced(testString: parsed, at: 8))
}

func testSyntaxBlockAttribute() throws {
let parser = getParser()

let parsed = parser.parse("a ```syntax``` c")
XCTAssertEqual(parsed.string, "a syntax c")

var effectiveRange = NSRange()
XCTAssertNotNil(parsed.attribute(.syntaxBlock, at: 3, effectiveRange: &effectiveRange))
XCTAssertEqual(effectiveRange, NSRange(location: 2, length: 6))

XCTAssertNil(parsed.attribute(.syntaxBlock, at: 0, effectiveRange: nil))
XCTAssertNil(parsed.attribute(.syntaxBlock, at: 9, effectiveRange: nil))
}

func testInlineCodeHasNoSyntaxBlockAttribute() throws {
let parser = getParser()

let parsed = parser.parse("a `code` c")
XCTAssertEqual(parsed.string, "a code c")
XCTAssertNil(parsed.attribute(.syntaxBlock, at: 3, effectiveRange: nil))
}

func testEmojiInsideSyntax() throws {
let parser = getParser()

Expand Down
10 changes: 10 additions & 0 deletions Source/CDMarkdownSyntax.swift
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,12 @@ open class CDMarkdownSyntax: CDMarkdownCommonElement {
// Since we use NSRange here, we need to count based on UTF16, alternatively could use NSString length property
let range = NSRange(location: range.location,
length: unescapedString.utf16.count)

// Add a custom attribute to the code block, so it can be detected later, e.g. when hit testing,
// since the styling of a code block and inline code can be identical
var attributes = self.attributes
attributes[.syntaxBlock] = NSNumber(value: true)

attributedString.addAttributes(attributes,
range: range)
// If the previous character was a newline then parser doesn't have to worry about
Expand Down Expand Up @@ -123,3 +129,7 @@ open class CDMarkdownSyntax: CDMarkdownCommonElement {
}
}
}

public extension NSAttributedString.Key {
static let syntaxBlock: NSAttributedString.Key = .init("syntaxBlock")
}
Loading