def untabify(text, width):
    """Replace tabs with spaces in text."""
    def next_stop(p):
        return width * ((p + width) // width)

    def pad(p):
        return ' ' * (next_stop(p) - p)

    out = list(text)
    pos = 0
    for cur, c in enumerate(out):
        if c == '\t':
            out[cur] = pad(pos)
            pos += len(out[cur])
        elif c == '\n':
            pos = 0
        else:
            pos += 1

    return ''.join(out)