import re
import html


def escape_markdown(content, escape_html=True):
    """
    Escape markdown characters so that when it's interpreted
    the converted text is not a valid markdown text.

    :param escape_html: html chars are escaped if True.
        Django already escapes HTML chars automatically when rendering
        templates so in those cases escape_html cam be safely set to False
    """
    # escape all markdown chars (e.g. replace * with \*)
    content = re.sub(r'([~_\*#\(\)\[\]`\-\+\\])', r'\\\1', content)

    # replace consecutive spaces/tabs/new lines with one space only
    content = re.sub(r'\s+', r' ', content)

    # escape html
    if escape_html:
        content = html.escape(content)

    return content