import re

from django import template
from django.utils.safestring import mark_safe

register = template.Library()


@register.filter
def highlight(text, q):
    q2 = "|".join(re.escape(word) for word in q.split())
    pattern = re.compile(r"(?P<filter>%s)" % q2, re.IGNORECASE)
    return mark_safe(
        re.sub(pattern, r"<span class='highlight'>\g<filter></span>", text)
    )
