from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe

@register.filter(needs_autoescape=True)
def my_safe(text, autoescape=True):
    regs = [re.compile('>>[\d]+(?! \(OP\))'), re.compile('>>[\d]+ \(OP\)')]
    for reg in regs:
        q = 0
        for x in re.finditer(reg, text):
            q += 1
        t = q
        e = 0
        while q != 0:
            w = re.finditer(reg, text)
            k = 0
            for x in w:
                if e == t - q:
                    if x.span()[0] == 0 and e == 0:
                        if reg == re.compile('>>[\d]+(?! \(OP\))'):
                            text = '<a class="link-reply" data-num="%s">' % text[2:x.span()[1]] +\
                                   text[:x.span()[1]] + '</a>' + conditional_escape(text[x.span()[1]:])
                        else:
                            text = '<a class="link-reply-thread" data-num="%s">' % text[2:x.span()[1] - 5] +\
                                   text[:x.span()[1]] + '</a>' + conditional_escape(text[x.span()[1]:])
                        break
                    else:
                        if k == t - q:
                            if reg == re.compile('>>[\d]+(?! \(OP\))'):
                                text = conditional_escape(text[:x.span()[0]]) +\
                                       '<a class="link-reply" data-num="%s">' % text[x.span()[0] +2:x.span()[1]] +\
                                       text[x.span()[0]:x.span()[1]] + '</a>' + conditional_escape(text[x.span()[1]:])
                            else:
                                text = conditional_escape(text[:x.span()[0]]) +\
                                       '<a class="link-reply-thread" data-num="%s">' % text[x.span()[0] + 2:x.span()[1] - 5] +\
                                       text[x.span()[0]:x.span()[1]] + '</a>' + conditional_escape(text[x.span()[1]:])
                            break
                k += 1
            e += 1
            q -= 1
    return mark_safe(text)