Wrapping code when exporting to an image with Pygments

Viewed 192

Reading through Pygments' formatters doc (https://pygments.org/docs/formatters/), I cannot find how to wrap long lines of code when using the ImageFormatter in order to export my highlighted code to a png image.

Here's my code:

from pygments.lexers import PythonLexer
from pygments.formatters import ImageFormatter
from pygments import highlight

code = 'print("Reading through Pygments\' formatters doc (https://pygments.org/docs/formatters/), I cannot find how to wrap code when using the ImageFormatter in order to export my highlighted code to a png image (i.e. let\'s say I want my image to be 600px, or 300 characters at font size, wide). It seems like wrapping is essential when exporting to an image, is the option missing from Pygments at this moment?")'

formatter = ImageFormatter()
with open("highlighted1.png", "wb") as f:
    f.write(highlight(code, PythonLexer(), formatter))

Which produces this image which (unusable for many applications): enter image description here

It seems like wrapping is essential when exporting to an image, is the option missing from Pygments at this moment?

1 Answers

The option to wrap lines is missing in the pygments library.

You could extend the ImageFormatter and override its format method to inserts new line tokens and wrap code lines. The format method is passed a list of tokens.

Focus on doing this procedure on Token.Literal.String.Double tokens to be more precise.

Otherwise, format code before it is passed in the highlight function properly. You can do that manually or programatically using a linter. Most linters do not fix long strings.

For example with autopep8, has bearly any effect on code

import autopep8

autopep8.fix_code(code, options=autopep8.parse_args(['']))

code has to be manually written as:

code = """ 
    print( 
        "Reading through Pygments' formatters doc(https://pygments.org/docs/formatters/), " 
        "I cannot find how to wrap code when using the ImageFormatter in order to export my " 
        "highlighted code to a png image (i.e. let's say I want my image to be 600px, " 
        "or 300 characters at font size, wide). It seems like wrapping is essential " 
        "when exporting to an image, is the option missing from Pygments at this moment?" 
    ) 
"""
Related