Printing with nested indentation

Is there some generic reusable solution for the problem of printing nested objects with indentation? For example a custom show method for an array-like type where each item should be printed with an indent. But the items themselves might need indents, too, so you cannot hardcore the amount of spaces. I tend to reimplement that whenever needed but it seems like this should be an IOContext parameter or something.

1 Like

The package PrettyPrint.jl does some sort of nested indentation, is it adequate?

Example with a Vector{Vector{Vector{Int64}}}:

using PrettyPrint
w = [[collect(1:rand(1:10)) for _ in 1:5] for _ in 1:3]
pprint(w)

# output:
[
  [
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    [1, 2, 3, 4, 5, 6],
    [1, 2, 3, 4, 5, 6, 7, 8, 9],
    [1, 2, 3, 4, 5, 6, 7],
    [1, 2],
  ],
  [
    [1, 2, 3],
    [1, 2, 3, 4],
    [1, 2, 3, 4, 5, 6],
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    [1, 2, 3, 4, 5, 6, 7],
  ],
  [
    [1,],
    [1, 2, 3, 4, 5, 6, 7],
    [1, 2],
    [1, 2, 3, 4, 5, 6, 7, 8, 9],
    [1, 2, 3, 4],
  ],
]

Thanks, although I was rather looking for a simpler solution that only handled indented printing. I found this which looks like it could work GitHub - tpapp/IndentWrappers.jl: Wrapper type for indentation management for plain text printing.

1 Like

IndentWrappers.jl looks like a very nice solution for that kind of problem. I was looking for something like that before but ended up writing my own messy solution. Please let us know if your going to revamp that package!

My personal wishlist for those IO wrappers would also include:

  • available line width (so you can line wrap things for the given terminal size without breaking the indent)
  • more complex prefixes besides spaces, for example something like lineprefix="│ " for nested tree-like printing with unicode box drawings.