import re


def shortify(string, width, tail=5, placeholder="[...]", collapse_whitespace=True):
    """ Truncate a string to fit within a given width. A bit like textwrap.shorten."""
    if collapse_whitespace:
        string = re.sub(r"\s+", " ", string)
    if width < 2 * tail + len(placeholder):
        raise ValueError(
            "Width parameter {} too short for tail={} and placeholder='{}'".format(
                width, tail, placeholder
            )
        )
    elif len(string) <= width:
        return string
    else:
        return string[: width - tail - len(placeholder)] + placeholder + string[-tail:]