import re


def collapse_spaces(string=None, markdown_compatible=False):
    """Strip outer and extra internal whitespace, preserving newlines.

    Args:
        string (str): The string from which to remove whitespace.
        markdown_compatible (bool): If True, be conservative in removing
                                    whitespace to avoid changing the
                                    meaning of markdown.

    Returns:
        str: The input string with excess whitespace removed.
    """
    if markdown_compatible:
        # Don't remove inner whitespace in case the user intended a <br>
        # by writing trailing spaces on a line other than the last one.
        return string.strip() if string else string
    else:
        return re.sub(r'\s+', ' ', string.strip()) if string else string