MarkdownEscaping.swift 920 B

1234567891011121314151617181920212223242526272829303132
  1. //
  2. // MarkdownEscaping.swift
  3. // Pods
  4. //
  5. // Created by Ivan Bruel on 18/07/16.
  6. //
  7. //
  8. import Foundation
  9. open class MarkdownEscaping: MarkdownElement {
  10. fileprivate static let regex = "\\\\."
  11. open var regex: String {
  12. return MarkdownEscaping.regex
  13. }
  14. open func regularExpression() throws -> NSRegularExpression {
  15. return try NSRegularExpression(pattern: regex, options: .dotMatchesLineSeparators)
  16. }
  17. open func match(_ match: NSTextCheckingResult, attributedString: NSMutableAttributedString) {
  18. let range = NSRange(location: match.range.location + 1, length: 1)
  19. // escape one character
  20. let matchString = attributedString.attributedSubstring(from: range).string
  21. if let escapedString = [UInt16](matchString.utf16).first
  22. .flatMap({ (value: UInt16) -> String in String(format: "%04x", value) }) {
  23. attributedString.replaceCharacters(in: range, with: escapedString)
  24. }
  25. }
  26. }