Skip to content

Instantly share code, notes, and snippets.

@MrMage
Created August 7, 2019 13:45
Show Gist options
  • Save MrMage/bcaabb20946700f75d838454216ecfb6 to your computer and use it in GitHub Desktop.
Save MrMage/bcaabb20946700f75d838454216ecfb6 to your computer and use it in GitHub Desktop.
public func attributeMarkdownString(_ string: String, defaultAttributes: [NSAttributedString.Key: Any]) -> NSAttributedString {
let result = NSMutableAttributedString(string: string, attributes: defaultAttributes)
let linkExpression = try! NSRegularExpression(pattern: "\\[([^]]+)\\]\\(([^)]+)\\)")
while let linkMatch = linkExpression.firstMatch(in: result.string, range: NSRange(location: 0, length: result.length)) {
let linkString = NSMutableAttributedString(attributedString: result.attributedSubstring(from: linkMatch.range(at: 1)))
linkString.addAttributes([
.foregroundColor: Appearance.colors.link,
.link: result.attributedSubstring(from: linkMatch.range(at: 2)).string,
], range: NSRange(location: 0, length: linkString.length))
result.replaceCharacters(in: linkMatch.range, with: linkString)
}
if let regularFont = defaultAttributes[.font] as? NSFont {
let boldFont = Appearance.fonts.of(regularFont.pointSize, weight: .bold)
let boldExpression = try! NSRegularExpression(pattern: "\\*\\*([^*]+)\\*\\*")
while let boldMatch = boldExpression.firstMatch(in: result.string, range: NSRange(location: 0, length: result.length)) {
let boldString = NSMutableAttributedString(attributedString: result.attributedSubstring(from: boldMatch.range(at: 1)))
boldString.addAttributes([
.font: boldFont
], range: NSRange(location: 0, length: boldString.length))
result.replaceCharacters(in: boldMatch.range, with: boldString)
}
let mediumFont = Appearance.fonts.of(regularFont.pointSize, weight: .medium)
let mediumExpression = try! NSRegularExpression(pattern: "\\*([^*]+)\\*")
while let mediumMatch = mediumExpression.firstMatch(in: result.string, range: NSRange(location: 0, length: result.length)) {
let mediumString = NSMutableAttributedString(attributedString: result.attributedSubstring(from: mediumMatch.range(at: 1)))
mediumString.addAttributes([
.font: mediumFont
], range: NSRange(location: 0, length: mediumString.length))
result.replaceCharacters(in: mediumMatch.range, with: mediumString)
}
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment