Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement