def format(msg, leftmargin=0, rightmargin=78):
    """Format a message by inserting line breaks at appropriate places.

    msg is the text of the message.
    leftmargin is the position of the left margin.
    rightmargin is the position of the right margin.

    Return the formatted message.
    """
    curs = leftmargin
    fmsg = ' ' * leftmargin
    for w in msg.split():
        l = len(w)
        if curs != leftmargin and curs + l > rightmargin:
            fmsg = fmsg + '\n' + ' ' * leftmargin
            curs = leftmargin
        if curs > leftmargin:
            fmsg = fmsg + ' '
            curs = curs + 1
        fmsg = fmsg + w
        curs = curs + l
    return fmsg
