from django.template import Library
from django.template.defaultfilters import stringfilter
from django.utils.html import escape
from django.utils.safestring import mark_safe, SafeData
from django.utils.text import normalize_newlines

register = Library()


@register.filter(is_safe=True, needs_autoescape=True)
@stringfilter
def linebreaksantislashn(value, autoescape=None):
    """
    Converts all newlines in a piece of plain text to '\n' string
    """
    autoescape = autoescape and not isinstance(value, SafeData)
    value = normalize_newlines(value)
    if autoescape:
        value = escape(value)
    return mark_safe(value.replace('\n', '\\n'))
