                         continue //it is matching on the same pattern, so skip it
                     }
                     if pattern.next() {
-                        pattern.end = index
-                        let range = advance(text.startIndex, pattern.start)...advance(text.startIndex, pattern.end)
+                        let range = advance(text.startIndex, pattern.start)...advance(text.startIndex, index)
                         //println("text range: \(text[range])")
                         if let match = pattern.matched {
                             let src = text[range]
                             let srcLen = countElements(src)
                             var replace = match(src,text,pattern.start)
-                            text.replaceRange(range, with: replace.text)
-                            let offset = (srcLen-countElements(replace.text))
-                            index -= offset
-                            if offset > 0 {
+                            if replace.attrs != nil {
+                                text.replaceRange(range, with: replace.text)
+                                let replaceLen = countElements(replace.text)
+                                index -= (srcLen-replaceLen)
                                 lastChar = char
+                                pattern.length = replaceLen
+                                pattern.attrs = replace.attrs
                             }
                         }
                         pending = pending.filter{$0 != pattern}
                         consumed = true
-                        //break
+                        if pattern.length > -1 {
+                            collect.append(pattern)
+                        }
                     }
                 } else {
                     if pattern.rewind() && !pattern.recursive {

            }
            index++
        }
        return text
    }
}

//

import Foundation
#if os(iOS)
import UIKit
#elseif os(OSX)
import Cocoa
#endif

//The support support class that keeps a track of the patterns while processing
class Pattern {
    var matched:((String,String,Int) -> (text: String,attrs: [NSObject : AnyObject]?))?
    var start = 0
    var length = -1
    var attrs: [NSObject : AnyObject]?
    var text: String
    var recursive: Bool
    var current: Character
    var mustFullfill = true
    var index = 0
    var rewindIndex = 0
    init(_ text: String, _ start: Int, _ recursive: Bool, _ matched: ((String,String,Int) -> (String,[NSObject : AnyObject]?))?) {
        self.mustFullfill = true
        self.recursive = recursive
        self.start = start
