The Hardest Program I've Ever Written – How a code formatter works (2015)
I wrote a simple formatter for outputting json values. It respects maximum line length.<p><a href="https://gist.github.com/nojvek/875d8cad1005da0b95da2840bbc894e6" rel="nofollow">https://gist.github.com/nojvek/875d8cad1005da0b95da2840bbc89...</a><p>It implements some of the ideas from <a href="https://blog.vjeux.com/2017/javascript/anatomy-of-a-javascript-pretty-printer.html" rel="nofollow">https://blog.vjeux.com/2017/javascript/anatomy-of-a-javascri...</a><p>Could be re-used for other languages very easily. The core is you have nested group chunks with (indent breakpoint, dedent breakpoint, separator breakpoint, more text chunks and child group chunks).<p>when formatting a single line, indent and dedunt breakpoints do nothing, but in multi line format, they specify how text will be laid out.<p>The algorithm is simple, try to format in single line if it fits within maxLineLength, if not break into multiple lines, and do that recursively.