+import Foundation
+
 public extension NSMutableAttributedString {
     // Add style
     public func addStyle(named styleName: String, regex: String) -> [NSTextCheckingResult]? {

        return self.style(style, regex: regex, tokenized: tokenized, replace: false)
    }
    
    // Set (replace) style
    public func setStyle(named styleName: String, regex: String, tokenized: Bool = true) -> [NSTextCheckingResult]? {
        let style = Style()
        for styleName in ZenCopy.manager.styleNamesFromStyleString(styleName) {

        return self.style(style, regex: regex, tokenized: tokenized, replace: true)
    }
    
    // Set (replace) style
    public func setStyle(named styleName: String, dataDetector: NSDataDetector, tokenized: Bool = true, replace: Bool = true) -> [NSTextCheckingResult]? {
        let matches = dataDetector.matchesInString(string, options: [], range: NSRange(location: 0, length: string.characters.count))
        let style = Style()
        for styleName in ZenCopy.manager.styleNamesFromStyleString(styleName) {
            if let s = ZenCopy.manager.config.styles?(name: styleName) {
                style.append(s)
            }
        }
        return self.style(style, matches: matches, tokenized: tokenized, replace: replace)
    }
    
    private func style(style: Style, matches: [NSTextCheckingResult], tokenized: Bool, replace: Bool) -> [NSTextCheckingResult]? {
        for match in matches {
            let range = (tokenized ? match.rangeAtIndex(match.numberOfRanges-1) : match.range)
            
            let attributes = ZenCopy.manager.attributesForStyle(style)
            if replace {
                self.setAttributes(attributes, range: range)
            } else if let attributes = attributes {
                self.addAttributes(attributes, range: range)
            }
        }
        
        return matches
    }
    
    // MARK: - Private
    private func style(style: Style, regex: String, tokenized: Bool, replace: Bool) -> [NSTextCheckingResult]? {
        do {
