def shorten(text, length):
    """Truncate the text if it is too long.
    """
    if len(text) > length:
        pos = text.rfind(' ', 0, length - 2)
        if pos == -1:
            pos = length - 3
        return text[:pos] + "..."
    else:
        return text