Advertisement
Guest User

Untitled

a guest
Aug 19th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. public func attributeMarkdownString(_ string: String, defaultAttributes: [NSAttributedString.Key: Any]) -> NSAttributedString {
  2. let result = NSMutableAttributedString(string: string, attributes: defaultAttributes)
  3.  
  4. let linkExpression = try! NSRegularExpression(pattern: "\\[([^]]+)\\]\\(([^)]+)\\)")
  5. while let linkMatch = linkExpression.firstMatch(in: result.string, range: NSRange(location: 0, length: result.length)) {
  6. let linkString = NSMutableAttributedString(attributedString: result.attributedSubstring(from: linkMatch.range(at: 1)))
  7. linkString.addAttributes([
  8. .foregroundColor: Appearance.colors.link,
  9. .link: result.attributedSubstring(from: linkMatch.range(at: 2)).string,
  10. ], range: NSRange(location: 0, length: linkString.length))
  11. result.replaceCharacters(in: linkMatch.range, with: linkString)
  12. }
  13.  
  14. if let regularFont = defaultAttributes[.font] as? NSFont {
  15. let boldFont = Appearance.fonts.of(regularFont.pointSize, weight: .bold)
  16. let boldExpression = try! NSRegularExpression(pattern: "\\*\\*([^*]+)\\*\\*")
  17. while let boldMatch = boldExpression.firstMatch(in: result.string, range: NSRange(location: 0, length: result.length)) {
  18. let boldString = NSMutableAttributedString(attributedString: result.attributedSubstring(from: boldMatch.range(at: 1)))
  19. boldString.addAttributes([
  20. .font: boldFont
  21. ], range: NSRange(location: 0, length: boldString.length))
  22. result.replaceCharacters(in: boldMatch.range, with: boldString)
  23. }
  24.  
  25. let mediumFont = Appearance.fonts.of(regularFont.pointSize, weight: .medium)
  26. let mediumExpression = try! NSRegularExpression(pattern: "\\*([^*]+)\\*")
  27. while let mediumMatch = mediumExpression.firstMatch(in: result.string, range: NSRange(location: 0, length: result.length)) {
  28. let mediumString = NSMutableAttributedString(attributedString: result.attributedSubstring(from: mediumMatch.range(at: 1)))
  29. mediumString.addAttributes([
  30. .font: mediumFont
  31. ], range: NSRange(location: 0, length: mediumString.length))
  32. result.replaceCharacters(in: mediumMatch.range, with: mediumString)
  33. }
  34. }
  35.  
  36. return result
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement