0

The ImageFormatter always creates a PNG output which width depends on the line length.

For example, this PNG is 192 pixels wide:

short

and this is 384:

long

Is there a setting in Pygments to emulate a 80 column output, so all images will have the same width?

This is the code I used to produce the examples:

#!/usr/bin/python3

from pygments import highlight
from pygments import lexers
from pygments.formatters.img import ImageFormatter
from pygments.styles import get_style_by_name, get_all_styles

lexer = lexers.get_lexer_by_name('C')

source_short = 'printf("%d\\n", i);'
source_long = 'printf("variable i is equal to %d.\\n", i);'

formatter = ImageFormatter(full = True, style = get_style_by_name('vim'))
open('short.png', 'wb').write(highlight(source_short, lexer, formatter))
formatter = ImageFormatter(full = True, style = get_style_by_name('vim'))
open('long.png', 'wb').write(highlight(source_long, lexer, formatter))
Jander
  • 59
  • 6

1 Answers1

0

Not sure if it's the best way, but worked for me.

This is MyFormatter, from ImageFormatter, in which the number of characters in line is always 80. The method format was minimally altered.

from pygments.formatter import Formatter
from pygments.util import get_bool_opt, get_int_opt, get_list_opt, \
    get_choice_opt, xrange
from PIL import Image, ImageDraw, ImageFont
import subprocess

class MyFormatter(ImageFormatter):
    def __init__(self, **options):
        super().__init__(**options)

    def format(self, tokensource, outfile):
        self._create_drawables(tokensource)
        self._draw_line_numbers()
        im = Image.new(
            'RGB',
            self._get_image_size(80, self.maxlineno), # always 80
            self.background_color
        )
        self._paint_line_number_bg(im)
        draw = ImageDraw.Draw(im)
        # Highlight
        if self.hl_lines:
            x = self.image_pad + self.line_number_width - self.line_number_pad + 1
            recth = self._get_line_height()
            rectw = im.size[0] - x
            for linenumber in self.hl_lines:
            y = self._get_line_y(linenumber - 1)
            draw.rectangle([(x, y), (x + rectw, y + recth)],
                       fill=self.hl_color)
        for pos, value, font, kw in self.drawables:
            draw.text(pos, value, font=font, **kw)
        im.save(outfile, self.image_format.upper())
Jander
  • 59
  • 6