Go to the documentation of this file.00001 import cStringIO
00002 import textwrap
00003
00004 __all__ = ["print_nested_list"]
00005
00006 def tokenize_list(obj):
00007 if isinstance(obj, list):
00008 yield "("
00009 for item in obj:
00010 for elem in tokenize_list(item):
00011 yield elem
00012 yield ")"
00013 else:
00014 yield obj
00015
00016 def wrap_lines(lines):
00017 for line in lines:
00018 indent = " " * (len(line) - len(line.lstrip()) + 4)
00019 line = line.replace("-", "_")
00020 line = textwrap.fill(line, subsequent_indent=indent, break_long_words=False)
00021 yield line.replace("_", "-")
00022
00023 def print_nested_list(nested_list):
00024 stream = cStringIO.StringIO()
00025 indent = 0
00026 startofline = True
00027 pendingspace = False
00028 for token in tokenize_list(nested_list):
00029 if token == "(":
00030 if not startofline:
00031 stream.write("\n")
00032 stream.write("%s(" % (" " * indent))
00033 indent += 2
00034 startofline = False
00035 pendingspace = False
00036 elif token == ")":
00037 indent -= 2
00038 stream.write(")")
00039 startofline = False
00040 pendingspace = False
00041 else:
00042 if startofline:
00043 stream.write(" " * indent)
00044 if pendingspace:
00045 stream.write(" ")
00046 stream.write(token)
00047 startofline = False
00048 pendingspace = True
00049
00050 for line in wrap_lines(stream.getvalue().splitlines()):
00051 print line