import re


def sort_pg_dump_output(output):
    """Sorts the tables, functions and indices dumped by pg_dump in
    alphabetic order. Also sorts all lists enclosed with parentheses
    in alphabetic order.
    """
    # Temporary replace newline with another character for easier
    # pattern matching.
    s = output.replace("\n", "§")

    # Parameter lists are enclosed with parentheses and every entry
    # ends with a comma last on the line.
    s = re.sub(r" \(§(.*?)§\);", lambda m: " (§" + ",§".join(sorted(m.group(1).split(",§"))) + "§);", s)

    # The header for all objects (tables, functions, indices, etc.)
    # seems to all start with two dashes and a space. We don't care
    # which kind of object it is here.
    s = "§-- ".join(sorted(s.split("§-- ")))

    # Switch our temporary newline replacement to real newline.
    return s.replace("§", "\n")