Hacker News new | ask | show | jobs
by cek 1487 days ago
I built a cross platform app to print 'pretty formatted' source code [1]. I didn't want to re-invent the wheel on formatting source code, so looked at all the existing libraries. Originally I figured formatting to HTML, and then building a print-friendly HTML render would work. But this proved super challenging. I tried a dozen HTML engines (including Chromium) but none gave me enough control to render just a single page of the original source file.

Then I noticed Pygments, a Python-based library for pretty formatting source code, has an option to output an ANSI formatted file. I quickly found a bunch of libraries that could render ANSI formatted text to a print canvas.

In the end, I put the original source code file through 'pygmentize -16m -o tempfile.an` (`16m` is the 16M color terminal ANSI formatter) and pipe the `tempfile.an` through a print-optimized renderer to actually print the source code.

ANSI escapes FTW!

[1] WinPrint - https://github.com/tig/winprint [2] https://pygments.org/

1 comments

> Originally I figured formatting to HTML, and then building a print-friendly HTML render would work. But this proved super challenging. [...] none gave me enough control to render just a single page of the original source file

Nothing like as powerful as your app and entirely tangential to the topic of ANSI escapes, but my preferred way to generate HTML from source code is simply:

    vim +TOhtml +wq +q path/to/source/file.ext
That will save an HTML version at `path/to/source/file.ext.html` (conforming to my .vimrc's syntax settings, theme, etc) and I'm happy enough with my browser or system's print dialog to go from there.
That is awesome. I've been using vim for years and never knew it had a command for this. I guess I should do more spelunking through the docs. Thanks!