Pretty printing is a hard problem. Read Philip Wadler's paper on implementing Haskell's pretty printer [0], and then maybe study the Rust library called `pretty` [1] which is an implementation of it for tree like structures.
[0] https://homepages.inf.ed.ac.uk/wadler/papers/prettier/pretti...