2 pygments.formatters.img
3 ~~~~~~~~~~~~~~~~~~~~~~~
5 Formatter for Pixmap output.
7 :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS.
8 :license: BSD, see LICENSE for details.
22 from PIL
import Image, ImageDraw, ImageFont
31 import winreg
as _winreg
35__all__ = [
'ImageFormatter',
'GifImageFormatter',
'JpgImageFormatter',
41 'NORMAL': [
'',
'Roman',
'Book',
'Normal',
'Regular',
'Medium'],
42 'ITALIC': [
'Oblique',
'Italic'],
44 'BOLDITALIC': [
'Bold Oblique',
'Bold Italic'],
48DEFAULT_FONT_NAME_NIX =
'DejaVu Sans Mono'
49DEFAULT_FONT_NAME_WIN =
'Courier New'
50DEFAULT_FONT_NAME_MAC =
'Menlo'
54 """When Python imaging library is not available"""
58 """When there are no usable fonts specified"""
63 Manages a set of fonts: normal, italic, bold, etc...
99 for name
in STYLES[
'NORMAL']:
107 for style
in (
'ITALIC',
'BOLD',
'BOLDITALIC'):
108 for stylename
in STYLES[style]:
114 if style ==
'BOLDITALIC':
125 '/Library/Fonts/',
'/System/Library/Fonts/'):
131 for name
in STYLES[
'NORMAL']:
139 for style
in (
'ITALIC',
'BOLD',
'BOLDITALIC'):
140 for stylename
in STYLES[style]:
146 if style ==
'BOLDITALIC':
152 for suffix
in (
'',
' (TrueType)'):
155 valname =
'%s%s%s' % (basename, style
and ' '+style, suffix)
162 raise FontNotFound(
'Font %s (%s) not found in registry' %
163 (basename, styles[0]))
172 for keyname
in keynames:
178 for style
in (
'ITALIC',
'BOLD',
'BOLDITALIC'):
183 if style ==
'BOLDITALIC':
188 except FontNotFound
as err:
203 raise FontNotFound(
'Can\'t open Windows font registry key')
207 Get the character size.
213 Get the text size (width, height).
215 font = self.
fonts[
'NORMAL']
223 Get the font based on bold and italic flags.
226 return self.
fonts[
'BOLDITALIC']
228 return self.
fonts[
'BOLD']
230 return self.
fonts[
'ITALIC']
232 return self.
fonts[
'NORMAL']
237 Create a PNG image from source code. This uses the Python Imaging Library to
238 generate a pixmap from the source code.
240 .. versionadded:: 0.10
242 Additional options accepted:
245 An image format to output to that is recognised by PIL, these include:
253 The extra spacing (in pixels) between each line of text.
258 The font name to be used as the base font from which others, such as
259 bold and italic fonts will be generated. This really should be a
260 monospace font to look sane.
262 Default: "Courier New" on Windows, "Menlo" on Mac OS, and
263 "DejaVu Sans Mono" on \\*nix
266 The font size in points to be used.
271 The padding, in pixels to be used at each edge of the resulting image.
276 Whether line numbers should be shown: True/False
281 The line number of the first line.
286 The step used when printing line numbers.
291 The background colour (in "#123456" format) of the line number bar, or
292 None to use the style background color.
297 The text color of the line numbers (in "#123456"-like format).
302 The number of columns of line numbers allowable in the line number
308 Whether line numbers will be bold: True/False
313 Whether line numbers will be italicized: True/False
317 `line_number_separator`
318 Whether a line will be drawn between the line number area and the
319 source code area: True/False
324 The horizontal padding (in pixels) between the line number margin, and
325 the source code area.
330 Specify a list of lines to be highlighted.
332 .. versionadded:: 1.2
337 Specify the color for highlighting lines.
339 .. versionadded:: 1.2
341 Default: highlight color of the selected style
346 aliases = [
'img',
'IMG',
'png']
347 filenames = [
'*.png']
349 unicodeoutput =
False
351 default_image_format =
'png'
355 See the class docstring for explanation of options.
357 if not pil_available:
359 'Python Imaging Library is required for this formatter')
364 if self.
style.background_color
is None:
370 options,
'image_format', [
'png',
'jpeg',
'gif',
'bmp'],
373 self.
line_pad = get_int_opt(options,
'line_pad', 2)
375 fontsize = get_int_opt(options,
'font_size', 14)
382 'line_number_chars', 2)
384 'line_number_bold',
False)
386 'line_number_italic',
False)
390 'line_number_separator',
True)
399 hl_lines_str = get_list_opt(options,
'hl_lines', [])
400 for line
in hl_lines_str:
406 self.
style.highlight_color)
or '#f90'
411 'formatter. Use -O style=<stylename> instead.')
415 Get the height of a line.
421 Get the Y coordinate of a line number.
427 Get the width of a character.
433 Get the X coordinate of a character position.
439 Get the actual position for a character and line position.
445 Get the actual position for the start of a line number.
451 Get the correct color for the token from the style.
453 if style[
'color']
is not None:
454 fill =
'#' + style[
'color']
461 Get the correct background color for the token from the style.
463 if style[
'bgcolor']
is not None:
464 bg_color =
'#' + style[
'bgcolor']
471 Get the correct font for the style.
473 return self.
fonts.get_font(style[
'bold'], style[
'italic'])
477 Get the required image size.
484 Remember a line number drawable to paint later.
497 Remember a single drawable tuple to paint later.
499 self.
drawables.append((pos, text, font, text_fg, text_bg))
503 Create drawables for the token content.
505 lineno = charno = maxcharno = 0
506 maxlinelength = linelength = 0
507 for ttype, value
in tokensource:
508 while ttype
not in self.
styles:
510 style = self.
styles[ttype]
527 temp_width, _ = self.
fonts.get_text_size(temp)
528 linelength += temp_width
529 maxlinelength = max(maxlinelength, linelength)
531 maxcharno = max(maxcharno, charno)
543 Create drawables for the line numbers.
554 Paint the line number background on the image.
571 Format ``tokensource``, an iterable of ``(tokentype, tokenstring)``
572 tuples and write it into ``outfile``.
574 This implementation calculates where it should draw each token on the
575 pixmap, then calculates the required pixmap size and draws the items.
595 for pos, value, font, text_fg, text_bg
in self.
drawables:
598 draw.rectangle([pos[0], pos[1], pos[0] + text_size[0], pos[1] + text_size[1]], fill=text_bg)
599 draw.text(pos, value, font=font, fill=text_fg)
608 Create a GIF image from source code. This uses the Python Imaging Library to
609 generate a pixmap from the source code.
611 .. versionadded:: 1.0
616 filenames = [
'*.gif']
617 default_image_format =
'gif'
622 Create a JPEG image from source code. This uses the Python Imaging Library to
623 generate a pixmap from the source code.
625 .. versionadded:: 1.0
629 aliases = [
'jpg',
'jpeg']
630 filenames = [
'*.jpg']
631 default_image_format =
'jpeg'
636 Create a bitmap image from source code. This uses the Python Imaging Library to
637 generate a pixmap from the source code.
639 .. versionadded:: 1.0
643 aliases = [
'bmp',
'bitmap']
644 filenames = [
'*.bmp']
645 default_image_format =
'bmp'