diff --git a/CDMarkdownKitTests/TestSyntax.swift b/CDMarkdownKitTests/TestSyntax.swift index 98d48b3f..946f7bd0 100644 --- a/CDMarkdownKitTests/TestSyntax.swift +++ b/CDMarkdownKitTests/TestSyntax.swift @@ -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() diff --git a/Source/CDMarkdownSyntax.swift b/Source/CDMarkdownSyntax.swift index 99064812..6384668f 100644 --- a/Source/CDMarkdownSyntax.swift +++ b/Source/CDMarkdownSyntax.swift @@ -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 @@ -123,3 +129,7 @@ open class CDMarkdownSyntax: CDMarkdownCommonElement { } } } + +public extension NSAttributedString.Key { + static let syntaxBlock: NSAttributedString.Key = .init("syntaxBlock") +}